1

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

ruleboy21
  • 5,510
  • 4
  • 17
  • 34
Khabr
  • 49
  • 7

3 Answers3

4

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);
ruleboy21
  • 5,510
  • 4
  • 17
  • 34
uminder
  • 23,831
  • 5
  • 37
  • 72
1

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)
ruleboy21
  • 5,510
  • 4
  • 17
  • 34
0

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 }, {})
nart
  • 1,508
  • 2
  • 11
  • 24