Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do reduce math.max to an array of objects

Tags:

javascript

I have an array of objects. I want to get the max out of the number attribute from the array:

[
  {number: 1000, name: "Josh"}, 
  {number: 2000, name: "Joker"}, 
  {number: 3000, name: "Batman"}
]

I'm using this solution but I keep getting NAN:

const max = arr.reduce((a, b) => Math.max(a.number, b.number));

My goal is to get the max and then store it in a variable

const x = { number: 3000, name: "Batman"}

How would I achieve it with reduce? It seems like it is only working with array of numbers.

like image 445
sinusGob Avatar asked Dec 20 '18 04:12

sinusGob


People also ask

How do you apply reduce on array of objects?

The reduce() method executes the function for each value of the array (non-empty array) from left to right. The reduce() method has the following syntax: let arr = [];arr. reduce(callback(acc, curVal, index, src), initVal);

Does math max work on arrays?

The Math. max() method compares the variable max with all elements of the array and assigns the maximum value to max .

Can Reduce be used on an object?

reduce will return the only value (object or otherwise) if the list object only has one item, without calling iterator function.


2 Answers

Done by simple reduce,

var arr=[{"number":1000,"name":"Josh"},{"number":2000,"name":"Joker"},{"number":3000,"name":"Batman"}]
   
var x = arr.reduce((acc, i)=>(i.number > acc.number ? i : acc))

console.log(x)
like image 106
Anurag Awasthi Avatar answered Oct 13 '22 13:10

Anurag Awasthi


With Array.prototype.reduce, you have to remember that the first argument passed to the callback is the accumulator. That is, the return value from the previous iteration.

Math.max returns a Number (or NaN if the operands cannot be compared numerically) so on the second iteration, you will be trying to compare the number property of a Number which won't work.

As an alternative to reduce, you might want to consider sorting the array. This could be beneficial if you want other properties like the smallest value.

// smallest to largest, use "b.number - a.number" to reverse
arr.sort((a, b) => a.number - b.number) 
arr[0] // smallest
arr[arr.length - 1] // largest
like image 20
Phil Avatar answered Oct 13 '22 14:10

Phil