tengo un objeto:
[ { name: "first name", rolePosition: 85 }, { name: "second name", rolePosition: 91 } ] ¿Cómo seleccionar un objeto con el valor más alto rolePosition ? En esta situación es 91
El problema se puede resolver con Array.reduce() de la siguiente manera:
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);Esta es tu solución.
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)Puede usar Math.max , Array.prototype.find para crear una función similar _.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 }, {})