Search code examples
d3.jscrossfilter

How to get the minimum and maximum value between a given range in data set in d3.js


I have a dataset in the format:

[{
  x: "2014-01-01",
  y: 1223 
},
 ...
 {x: "2017-01-01",
  y: 143
 }
 ];

and given a range for example

["2015-01-01","2016-01-01"]

I would like to find the minimum and maximum y value between those 2 ranges.

How can I do this in d3?

currently, I use the following function to find the min/max

d3.min(formattedData, function(d) { return d.y; }), 

d3.max(formattedData, function(d) { return d.y; });

I'm not sure how to apply the range in there

the dates are already parsed so don't worry about that part

I apply the following function on all the x values ie. parseDate.parse(x)

parseDate = d3.time.format('%Y-%m-%d');

Solution

  • If your list is extremely long and you don't want to loop it more than once, you can do this all in one call:

    <!DOCTYPE html>
    <html>
    
    <head>
      <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
    </head>
    
    <body>
      <script>
        var input = [{
            x: new Date("2014-01-01"),
            y: 1223
          }, {
            x: new Date("2015-06-01"),
            y: 12
          }, {
            x: new Date("2015-07-01"),
            y: 1025
          }, {
            x: new Date("2015-08-01"),
            y: 125
          }, {
            x: new Date("2017-01-01"),
            y: 143
          }],
          minDate = new Date("2015-01-01"),
          maxDate = new Date("2016-01-01");
    
        var minMax = d3.extent(input, function(d) {
          if (d.x <= minDate || d.x >= maxDate){
            return NaN;
          }
          return d.y;
        })
        console.log(minMax);
      </script>
    </body>
    
    </html>