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

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]);

Use JS spread operator to avoid extra coding:

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

You have to iterate through the array. AFAIK there is no array_min in JS.

var i, min = arr[0];
for (i=1; i<arr.length; i++)
    min = Math.min(min, arr[i]);

Tags:

Javascript