Derreck Derreck - 28 days ago 10
Javascript Question

D3.js-How can I get the maximum value of a specified key in an object

I have this array

data =[
{id: "27", name: "Burger King", sum: "900"},
{id: "4", name: "Eggs(4)", sum: "896"},
{id: "5", name: "Hamburger", sum: "910"},
{id: "8", name: "Mac & Cheese", sum: "761"},
{id: "56", name: "McDonalds", sum: "1260"}
];


I want to extract the maximum value for the sum and append it to an li tag. This is my d3.js code:

function add_max(){
d3.select('#my_ul_tag).data(data).append('li')
.text(function(d) {
return 'Max ' + d3.max(d.sum);
});

}
add_max();


What this does is gets the value from the first object in the array (in the above example 900) and then treats it like an array and extracts the maximum value, in this case 9. So, if the value was 785, then it would return 8 because it is larger than 7 and 5. The string "Max 8 " would be appended correctly to the ul, but the value "8" is not right. What I am looking for is the maximum value of 1260. That is strange to me.
Can anybody help me understand this problem? Thank you!

Answer

Your properties are strings but you want to treat them as numbers. Cleaning this whole thing up the proper d3 solution is:

function add_max() {
  var maxValue = d3.max(data, function(d){
    return +d.sum; //<-- convert to number
  })
  d3.select('#my_ul_tag').append('li')
    .text(maxValue);
}

Running code:

<!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>
  
  <ul id="my_ul_tag"></ul>
  
  <script>
    var data = [{
      id: "27",
      name: "Burger King",
      sum: "900"
    }, {
      id: "4",
      name: "Eggs(4)",
      sum: "896"
    }, {
      id: "5",
      name: "Hamburger",
      sum: "910"
    }, {
      id: "8",
      name: "Mac & Cheese",
      sum: "761"
    }, {
      id: "56",
      name: "McDonalds",
      sum: "1260"
    }];

    function add_max() {
      var maxValue = d3.max(data, function(d){
        return +d.sum;
      })
      d3.select('#my_ul_tag').append('li')
        .text(maxValue);
    }
    
    add_max();
  </script>
</body>

</html>

Comments