1

In an array of objects, I'd like to select the one that has the largest value in one of it's fields.

I get how to select the value itself:

Math.max.apply(Math, list.map(function (o) { return o.DisplayAQI; }))

... but I am not sure how to do the above but return the object itself.

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
americanslon
  • 4,048
  • 4
  • 32
  • 57

3 Answers3

6

You can use reduce to get the object with the highest DisplayAQI

let list = [ {DisplayAQI : 20}, {DisplayAQI : 100}, {DisplayAQI : 200}, {DisplayAQI : 10} ];

let result = list.reduce((c, v) => c.DisplayAQI > v.DisplayAQI ? c : v);

console.log(result);

Doc: reduce()

Eddie
  • 26,593
  • 6
  • 36
  • 58
  • 1
    good solution, as the first thing that hit my mind after listening the question was sorting. But, we can exploit reduce in this case to achieve the result. – Abhishek Kumar May 29 '18 at 15:42
  • 1
    Sorting is very slow compared to reduce @AbhishekKumar – baao May 29 '18 at 15:43
0
myObjectArray.sort ( (myObject1, myObject2) => {
return myObject1.field - myObject2.field
})[0]

Simply sort the array according to your field, and get the zero index element.

Abhishek Kumar
  • 2,501
  • 10
  • 25
0

Alternatively you can sort the array of object in descending order and the get the element from the 0th index

let list = [{
  DisplayAQI: 20
}, {
  DisplayAQI: 100
}, {
  DisplayAQI: 200
}, {
  DisplayAQI: 10
}];

let result = list.sort(function(a, b) {
  return b.DisplayAQI - a.DisplayAQI

})[0];
console.log(result)
brk
  • 48,835
  • 10
  • 56
  • 78