Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3.js Selecting min/max value from an array of arrays (nesting d3.extent)

I have a bit of code that takes the values of the elements in a column and places them into an array:

var someArray = new Array(rows.selectAll("td").filter(function(d,i)
    {
        if(i==2) //index of the cells in the rows where I retrieve the data  
        {
            return (d3.select(this))
        }
    }));

^ creates an array of array[1]s that have the value of the cell in the element such as "2.6" or "5.4"

When I try to use:

console.log(d3.min(someArray)); 

I get [Array[1], Array[1], Array[1],...] whereas what I need returned is the lowest, and then largest value amongst those arrays (this will be used in d3.scale.linear().domain([The minimum value,The maximum value])

like image 405
user3285806 Avatar asked Feb 13 '14 17:02

user3285806


3 Answers

You just need to nest the calls:

var min = d3.min(arrayOfArrays, function(d) { return d3.min(d); });

To get both max and min at the same time, use d3.extent():

// extent[0] == min, extent[1] == max
var extent = d3.extent(arrayOfArrays, function(d) { return d3.extent(d); });

Unfortunately you can't get the extent in the nested case -- you'll have to do min and max separately.

like image 91
Lars Kotthoff Avatar answered Oct 21 '22 16:10

Lars Kotthoff


For a nested version of d3.extend, a little ES6 goodness and the possibility to have an accessor you can use the following:

function nestedExtent(data, accessor) {
  return data.reduce(([extentMin, extentMax], d) => {
    const [min, max] = extent(d, accessor);

    return [
      Math.min(extentMin, min),
      Math.max(extentMax, max),
    ];
  }, [Infinity, -Infinity]);
}
like image 34
Johnny Avatar answered Oct 21 '22 17:10

Johnny


I was looking for a way to nest d3.extent and I couldn't find one, so I resorted to figuring it out for myself and this is what I came up with...

var extent = d3.extent(arrayOfArrays.reduce(function(m,d){return m.concat(d)},[]))
like image 23
Cool Blue Avatar answered Oct 21 '22 16:10

Cool Blue