Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why using Math.max as a parameter does not work on this scenario? [duplicate]

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.

like image 356
Pablo Lozano Avatar asked Aug 28 '17 16:08

Pablo Lozano


People also ask

Why is math MAX () less than math MIN ()?

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 .

How does Math MAX work?

The Math.max() function returns the largest of the numbers given as input parameters, or - Infinity if there are no parameters.

Can math Max take an array?

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

How to get MAX value in javascript array?

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.


1 Answers

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);
like image 182
Andy Carlson Avatar answered Oct 04 '22 23:10

Andy Carlson