sf8193
sf8193

Reputation: 635

possible to use math.max for array of objects?

I see answers like this for getting the biggest number in an array,

var arr = [1, 2, 3];
var max = Math.max(...arr);

But what about doing this for an array of objects, each of which have a number field, something like this

class test {
   number: x
   other_fields
}

var arr = [test1, test2, test3];
var max = Math.max(...arr);

Upvotes: 2

Views: 514

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370799

Use .map to transform the array of objects into an array of numbers first:

var max = Math.max(
  ...arr.map(obj => obj.number)
);

const obj1 = {
   number: 2,
   prop: 'val'
};
const obj2 = {
   number: 2,
   prop: 'val'
};

var arr = [obj1, obj2];
var max = Math.max(
  ...arr.map(obj => obj.number)
);
console.log(max);

If you need an object and not just the number, use reduce instead:

const obj1 = {
   number: 2,
   prop: 'val'
};
const obj2 = {
   number: 2,
   prop: 'val'
};

var arr = [obj1, obj2];
const largestObj = arr.reduce((a, obj) => a.number > obj.number ? a : obj);
console.log(largestObj);

Upvotes: 5

Related Questions