Richard
Richard

Reputation: 65550

Find the maximum value in an object where the keys are arrays?

Using D3, how can I find the maximum value in an object where all the values are arrays of floats?

  var data = {
    "point1": { 
       "level1": [...],
       "level2": [...]
    },
    ...
  };

I read Mike's answer on finding the max of a nested array, but I'm not sure what to do here since this is an object of arrays.

Currently I'm doing this, which is awful:

  var c1Max = d3.max(data.point1.level1, function(d) { return d.value; });
  var c2Max = d3.max(data.point1.level2, function(d) { return d.value; });
  var c3Max = d3.max(data.point2.level1, function(d) { return d.value; });
  var c4Max = d3.max(data.point2.level2, function(d) { return d.value; });
  var c5Max = d3.max(data.point3.level1, function(d) { return d.value; });
  var c6Max = d3.max(data.point3.level2, function(d) { return d.value; });
  var max = d3.max([c1Max, c2Max, c3Max, c4Max, c5Max, c6Max]);

Maybe I should iterate over all the keys? Or maybe I could flatten the data object somehow? Or maybe there's a nicer way.

Upvotes: 4

Views: 4788

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

You can use d3.entries to convert the object into something you can iterate over:

var max = d3.max(d3.entries(data), function(d) {
    return d3.max(d3.entries(d.value), function(e) {
        return d3.max(e.value);
    });
});

In this particular case (keys not required) you can of course also use d3.values, which makes the above code a bit shorter.

To make it work with the structure in your jsfiddle, you need this code:

var max1 = d3.max(d3.entries(data), function(d) {
  return d3.max(d3.entries(d.value), function(e) {
      return d3.max(e.value, function(f) { return f.value; });
  });
});

Upvotes: 4

Related Questions