Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the min elements inside an array in javascript?

Tags:

javascript

This is what I tried:

Math.min([1,2,3])

But only get NaN...

like image 246
compile-fan Avatar asked Mar 26 '11 11:03

compile-fan


2 Answers

use apply:

Math.min.apply(null,[1,2,3]); //=> 1

From devguru:

Function.apply(thisArg[, argArray]) the apply method allows you to call a function and specify what the keyword this will refer to within the context of that function. The thisArg argument should be an object. Within the context of the function being called, this will refer to thisArg. The second argument to the apply method is an array. The elements of this array will be passed as the arguments to the function being called. The argArray parameter can be either an array literal or the deprecated arguments property of a function.

In this case the first argument is of no importance (hence: null), the second is, because the array is passed as arguments to Math.min. So that's the 'trick' used here.

[edit nov. 2020] This answer is rather old. Nowadays (with Es20xx) you can use the spread syntax to spread an array to arguments for Math.min.

Math.min(...[1,2,3]);
like image 184
KooiInc Avatar answered Oct 13 '22 22:10

KooiInc


Use JS spread operator to avoid extra coding:

console.log(Math.min(...[1,2,3]))
like image 28
Eugen Sunic Avatar answered Oct 13 '22 22:10

Eugen Sunic