-3

I would like to get the hightest value of array (only the 'y'), how can I do that?

I'm getting only the value of array setting into[] like values[0]

data = [
    {
      values: [
        { x:'2017-01', y: 1.2 },
        { x:'2017-02', y: 1.3 },
        { x:'2017-03', y: 1.5 },
        { x:'2017-04', y: 1.6 },
        { x:'2017-05', y: 1.8 },
        { x:'2017-06', y: 1.9 },
        { x:'2017-07', y: 1.5 },
        { x:'2017-08', y: 1.7 },
        { x:'2017-09', y: 1.5 },
        { x:'2017-10', y: 0 }
      ]
    }
  ];
  
  data.forEach(function(d) {
    console.log(Math.max(d.values[0].y));
  });
deleting
  • 429
  • 1
  • 8
  • 19

2 Answers2

5

I assume that you want to get the object with maximum value y from data[0].values, since data itself is an array with only one element.

If you wanted to only get the max value of y (1.9), you could use Math.max, but if you want to get the whole object that has maximum y, you would need to iterate through the array again to find the object that has y == 1.9.

Instead you can do both at once using Array.prototype.reduce, which iterates through the array calling the callback on each element similarly to Array.prototype.forEach, except the value you return from the callback on each iteration is passed as an argument to the next iteration

data = [
    {
      values: [
        { x:'2017-01', y: 1.2 },
        { x:'2017-02', y: 1.3 },
        { x:'2017-03', y: 1.5 },
        { x:'2017-04', y: 1.6 },
        { x:'2017-05', y: 1.8 },
        { x:'2017-06', y: 1.9 },
        { x:'2017-07', y: 1.5 },
        { x:'2017-08', y: 1.7 },
        { x:'2017-09', y: 1.5 },
        { x:'2017-10', y: 0 }
      ]
    }
  ];
  
var max = data[0].values.reduce( function( maxSoFar, current ) {
    // If current.y is larger than maxSoFar.y, return current
    // so that it becomes maxSoFar for the next iteration
    return current.y > maxSoFar.y ? current : maxSoFar;
});

console.log( max );
Paul
  • 139,544
  • 27
  • 275
  • 264
3

The values are a property of the 1st object (index 0) of the array - data[0].values. Get all y values using Array#map, and apply Math#max to get the maximum:

var data = [{"values":[{"x":"2017-01","y":1.2},{"x":"2017-02","y":1.3},{"x":"2017-03","y":1.5},{"x":"2017-04","y":1.6},{"x":"2017-05","y":1.8},{"x":"2017-06","y":1.9},{"x":"2017-07","y":1.5},{"x":"2017-08","y":1.7},{"x":"2017-09","y":1.5},{"x":"2017-10","y":0}]}];
  
var result = Math.max.apply(null, data[0].values.map(function(o) {
  return o.y;
}));

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209