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.
1. Using Math.min() method
// ONLINE-RUNNER:browser;
const array = [3, 1, 2];
const result = Math.min(...array);
console.log(result); // 1
or:
// ONLINE-RUNNER:browser;
const array = [3, 1, 2];
const result = Math.min.apply(null, array);
console.log(result); // 1
2. Using reduce() method
// ONLINE-RUNNER:browser;
const array = [3, 1, 2];
const result = array.reduce((a, b) => Math.min(a, b));
console.log(result); // 1
3. By comparing items in array
// ONLINE-RUNNER:browser;
const array = [3, 1, 2];
let result = Infinity;
for(const item of array) {
if(item < result) {
result = item;
}
}
console.log(result); // 1
4. Add function to Array.prototype
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.
// ONLINE-RUNNER:browser;
var numbers = [2, 3, 1];
Array.prototype.min = function() {
return Math.min.apply(null, this);
};
console.log(numbers.min()); // 1