Skip to content Skip to sidebar Skip to footer

D3 Js Get A D3.max From An Object That Contains A Specific Key Value

I have the following dataset and am trying to get the d3.max to specify a domain for a scale, but want the d3.max value only from objects that have the key enabled=true. How can th

Solution 1:

If you want it in one line:

var max = d3.max(data.filter(d => d.enabled === "true"), e => d3.max(e.values, f => f.value));

Or, without the arrow functions:

var max = d3.max(data.filter(function(d) {
    return d.enabled === "true";
}), function(e) {
    return d3.max(e.values, function(f) {
        return f.value;
    });
});

Here is a demo:

var data = [{
  "key": "name1",
  "enabled": "true",
  "values": [{
    "date": "2016-09-13T02:11:44Z",
    "value": "100",
  }, {
    "date": "2016-09-13T02:11:44Z",
    "value": "200",
  }]
}, {
  "key": "name2",
  "enabled": "false",
  "values": [{
    "date": "2016-09-13T02:11:44Z",
    "value": "400",
  }, {
    "date": "2016-09-13T02:11:44Z",
    "value": "500",
  }]
}];

var max = d3.max(data.filter(d => d.enabled === "true"), e => d3.max(e.values, f => f.value));

console.log(max);
<scriptsrc="https://d3js.org/d3.v4.min.js"></script>

It accepts more than one object with enabled: "true", check this second demo, I put another object in your data array:

var data = [{
  "key": "name1",
  "enabled": "true",
  "values": [{
    "date": "2016-09-13T02:11:44Z",
    "value": "100",
  }, {
    "date": "2016-09-13T02:11:44Z",
    "value": "200",
  }]
}, {
  "key": "name2",
  "enabled": "false",
  "values": [{
    "date": "2016-09-13T02:11:44Z",
    "value": "400",
  }, {
    "date": "2016-09-13T02:11:44Z",
    "value": "500",
  }]
},{
  "key": "name1",
  "enabled": "true",
  "values": [{
    "date": "2016-09-13T02:11:44Z",
    "value": "800",
  }, {
    "date": "2016-09-13T02:11:44Z",
    "value": "200",
  }]
}];

var max = d3.max(data.filter(d => d.enabled === "true"), e => d3.max(e.values, f => f.value));

console.log(max);
<scriptsrc="https://d3js.org/d3.v4.min.js"></script>

Post a Comment for "D3 Js Get A D3.max From An Object That Contains A Specific Key Value"