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);
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With