EN
JavaScript - min value in array
0 points
In this article, we would like to show you how to find the minimum value in an array working with JavaScript.
xxxxxxxxxx
1
const array = [3, 1, 2];
2
3
const result = Math.min(array);
4
5
console.log(result); // 1
or:
xxxxxxxxxx
1
const array = [3, 1, 2];
2
3
const result = Math.min.apply(null, array);
4
5
console.log(result); // 1
xxxxxxxxxx
1
const array = [3, 1, 2];
2
3
const result = array.reduce((a, b) => Math.min(a, b));
4
5
console.log(result); // 1
xxxxxxxxxx
1
const array = [3, 1, 2];
2
3
let result = Infinity;
4
5
for(const item of array) {
6
if(item < result) {
7
result = item;
8
}
9
}
10
11
console.log(result); // 1
In this example, we add a new function min()
to the Array()
object so we can use it on every array as it was a built-in function.
xxxxxxxxxx
1
var numbers = [2, 3, 1];
2
3
Array.prototype.min = function() {
4
return Math.min.apply(null, this);
5
};
6
7
console.log(numbers.min()); // 1