EN
JavaScript - Math.min() method example
8 points
The Math.min()
function returns the smallest number from given numbers.
xxxxxxxxxx
1
var min = Math.min(2, 5);
2
console.log(min); // 2
3
4
console.log( Math.min(1) ); // 1
5
console.log( Math.min(1, 2) ); // 1
6
console.log( Math.min(1, 2, 3) ); // 1
7
console.log( Math.min(3, 25, -6, 0) ); // -6
8
9
console.log( Math.min(-5, -2, -7) ); // -7
10
console.log( Math.min(2, 1, NaN) ); // NaN
11
console.log( Math.min() ); // -Infinity
Math.min()
function usage with an array in ES5 and ES6 example:
xxxxxxxxxx
1
var array = [7, 10, 5, 8];
2
3
// In ES5
4
console.log(Math.min.apply(Math, array)); // 5
5
6
// In ES6 - Spread Operator (...) has been introduced
7
console.log(Math.min(array)); // 5
8
console.log(Math.min(100, array, 120, [151, 152])); // 5
Syntax | Math.min(number1, number2, ...numbers) |
Parameters | number1, number2, ...numbers - integer or float number values (primitive values). |
Result |
Minimal It returns It returns |
Description | min is a static method that takes several arguments and returns the smallest value. |
This approach uses reduce
method to find the minimum value inside an array. By making small modifications of Math.min(a, b)
instruction we are able to find minimal value inside properties of a
and b
variables.
xxxxxxxxxx
1
var array = [1, 2, 3];
2
3
var result = array.reduce(function(a, b) {
4
return Math.min(a, b);
5
});
6
7
console.log(result); // 1
This approach uses recurrence to find the minimum value inside the array or nested arrays.
xxxxxxxxxx
1
function findMin() {
2
function checkEntry(entry) {
3
if (entry instanceof Array) {
4
return findMin.apply(null, entry);
5
}
6
return entry;
7
}
8
if (arguments.length > 0) {
9
var result = checkEntry(arguments[0]);
10
for (var i = 1; i < arguments.length; ++i) {
11
var value = checkEntry(arguments[i]);
12
if (value < result) {
13
result = value;
14
}
15
}
16
return result;
17
}
18
return NaN;
19
}
20
21
console.log(findMin(1, 2, 3, [4, 5, 6],[7, 8, [9, 10]])); // 1