Skip to content Skip to sidebar Skip to footer

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'}, {

Solution 1:

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

functionadd_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><scriptdata-require="d3@4.0.0"data-semver="4.0.0"src="https://d3js.org/d3.v4.min.js"></script></head><body><ulid="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"
    }];

    functionadd_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>

Solution 2:

You could use reduce for it. This proposal returns the max value of a digit of sum.

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" }],
    max = data.map(function (o) {
        return o.sum.split('').reduce(function (r, b) {
            return r > b ? r : b;
        }, 0);            
    });
   
console.log(max);

Post a Comment for "D3.js-how Can I Get The Maximum Value Of A Specified Key In An Object"