Returning the object from the array with the highest property value
we need to get the b value from the object with the highest a value ...
var myArr = [
{
a: 1,
b: 15
},
{
a: 2,
b: 30
}
];
we tried the following, but it just returns the maximum value of a, not b.
var res = Math.max.apply(Math,myArr.map(function(o){return o.a;}))
var blah = getByValue(myArr);
source to share
Use Array # to shrink , and on each iteration take the object with the highest value a
:
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);
source to share
You can sort the copy, then get the first or last, depending on the sorting direction:
var myArr = [
{
a: 1,
b: 15
},
{
a: 2,
b: 30
}
];
var highest = myArr.slice().sort((a,b)=>a.a-b.a).pop().b
console.log(highest)
source to share
Using abbreviation
You can use .reduce()
to find the element with the maximum value a
and then just get its value b
like:
var myArr = [{
a: 1,
b: 15
},
{
a: 2,
b: 30
}
];
var max = myArr.reduce(function(sum, value) {
return (sum.a > value.a) ? sum : value;
}, myArr[0]);
console.log(max.b);
Using sort
A slightly more unorthodox approach is to use .sort()
to sort the array in descending order in terms of its property a
, and then get the value of the first element b
, for example:
var myArr = [{
a: 1,
b: 15
},
{
a: 2,
b: 30
}
];
var max = myArr.sort(function(value1, value2) {
return value1.a < value2.a;
})[0];
console.log(max.b);
source to share