0

I am trying to get max value from all 'value' property. Following code giving max value as 8, where as max value in data is 60.

How to get correct maximum value for the following data?

data = [
        { type: "type1", value: "60" },
        { type: "type2", value: "38" },
        { type: "type3", value: "4" },
        { type: "type4", value: "5" },
        { type: "type5", value: "8" },
        { type: "type6", value: "2" },
      ];
      console.log(
        d3.max(data, (d) => {
          return d.value;
        })
      );// expecting 60 but getting 8
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
ram
  • 237
  • 2
  • 14

2 Answers2

0

A simple one liner suffices. Math.max(...data.map(({value}) => +value))

Moritz Roessler
  • 8,542
  • 26
  • 51
0

First you need to turn those values into actual numbers. Or if you need them into a string, you can use parseInt() to turn them into numbers.

data = [
  { type: "type1", value: 60 },
  { type: "type2", value: 38 },
  { type: "type3", value: 4 },
  { type: "type4", value: 5 },
  { type: "type5", value: 8 },
  { type: "type6", value: 2 },
];

let max = 0;

data.forEach(obj => {
  if (obj.value > max) max = obj.value
});
Herbie Vine
  • 1,643
  • 3
  • 17
  • 32
  • Why do you use `map` when you neither return a mapped value, nor use the mapped array.?`forEach` would make more sense. – Moritz Roessler Jun 19 '20 at 11:59
  • `forEach()` is actually quite slower compared to `map()`. If you can use `map()`, it's best to use it. See more about this topic here: https://medium.com/@JeffLombardJr/understanding-foreach-map-filter-and-find-in-javascript-f91da93b9f2c – Herbie Vine Jun 19 '20 at 12:09
  • That's actually not true. `map` is 60-80% slower than `forEach` on Chrome 83. See this [jsperf](https://jsperf.com/foreach-vs-map-x3jf) – Moritz Roessler Jun 19 '20 at 12:17
  • 1
    Oh ok then... That's for the clarification . Will also edit my answer – Herbie Vine Jun 19 '20 at 12:25