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.
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);
The Math. max() method compares the variable max with all elements of the array and assigns the maximum value to max .
reduce will return the only value (object or otherwise) if the list object only has one item, without calling iterator function.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With