I have an object:
[
{
name: "first name",
rolePosition: 85
},
{
name: "second name",
rolePosition: 91
}
]
How to select an object with the highest rolePosition
value? In this situation is 91
I have an object:
[
{
name: "first name",
rolePosition: 85
},
{
name: "second name",
rolePosition: 91
}
]
How to select an object with the highest rolePosition
value? In this situation is 91
The problem can be solved with Array.reduce()
as follows:
const arr = [{ name: "first name", rolePosition: 85 }, { name: "second name", rolePosition: 91 }];
const result = arr.reduce((prev, curr) => prev.rolePosition > curr.rolePosition ? prev : curr , {});
console.log(result);
This is your solution.
const arr = [
{
name: "first name",
rolePosition: 85
},
{
name: "second name",
rolePosition: 91
}
];
const numbers = [];
arr.forEach(el => numbers.push(el.rolePosition));
const max = Math.max(...numbers);
console.log(max)
You can use Math.max
, Array.prototype.find
to create similar function _.maxBy lodash
const maxBy = (arr, func) => {
const max = Math.max(...arr.map(func))
return arr.find(item => func(item) === max)
}
maxBy([{ test: 1 }, { test: 2 }], o => o.test)
// { test: 2 }
// or use reduce
const maxItem = arr.reduce(function(a, b) { return a.rolePosition >= b.rolePosition ? a : b }, {})