I was answering a question related to Array.reduce by using Math.max in my example and I found something that I don't understand:
This works:
let values=[4,5,6,77,8,12,0,9];
let max=values.reduce((acc,curr) => Math.max(acc,curr),0);
console.log(max);
But if I try something like this:
let values=[4,5,6,77,8,12,0,9];
let max=values.reduce(Math.max,0);
console.log(max);
It returns NaN.
I thought that the context was the reason, so I wrote the following:
let max=Math.max;
console.log(max(2,5));
But it worked as expected!
What am I missing? MDN says that:
If at least one of the arguments cannot be converted to a number, NaN is returned.
max() starts with a search value of -Infinity , because any other number is going to be greater than -Infinity. Similarly, Math. min() starts with the search value of Infinity : “If no arguments are given, the result is Infinity .
The Math.max() function returns the largest of the numbers given as input parameters, or - Infinity if there are no parameters.
The Math. max() method compares the variable max with all elements of the array and assigns the maximum value to max .
Method 1: Using Math.min() and Math.max() The min() and max() methods of the Math object are static functions that return the minimum and maximum element passed to it. These functions could be passed an array with the spread(…) operator.
What you're missing is that the callback to reduce
has more parameters than just the accumulator and current array value. It actually has 4.
See the docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Description
The four parameters:
accumulator
currentValue
currentIndex
array (a reference to the array itself)
The problem is the fourth parameter, it's the array itself that reduce
was called on. Math.max
can't handle arrays, so it returns NaN
.
EDIT: instead, you can use the apply
method or the new spread operator!
let values = [4,5,6,77,8,12,0,9];
let max = Math.max.apply(null, values);
let maxAnotherWay = Math.max(...values);
OR, if you happen to be using Lodash, the _.ary
method lets you wrap functions in another function that limits its arity:
let values = [4,5,6,77,8,12,0,9];
let max = values.reduce(_.ary(Math.max, 2),0);
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