Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From an array of objects, how to return property `b` of the object that has the highest property `a`?

I need to get the value of the property b from the object with the highest value of the property a.

var myArr = [
  {
    a: 1,
    b: 15
  },
  {
    a: 2,
    b: 30
  }
];

I tried the following, but it just returns the highest value of a, rather than of b.

var res = Math.max.apply(Math,myArr.map(function(o){return o.a;});
var blah = getByValue(myArr);
like image 812
Romain Gaget Avatar asked Aug 03 '17 14:08

Romain Gaget


People also ask

How do you find the object of an array?

To find an object in a JavaScript array, use the array. find() method. The find() method searches the provided object inside the array, and if the method finds it, it returns the object.


1 Answers

Use Array#reduce, and on each iteration take the object with the highest a value:

var myArr = [{"a":1,"b":15},{"a":2,"b":30}];

var result = myArr.reduce(function(o, o1) {
  return o.a > o1.a ? o : o1;
}).b;

console.log(result);
like image 129
Ori Drori Avatar answered Oct 18 '22 10:10

Ori Drori