THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorial explains different ways to find the smallest number in an array of elements.
There are multiple ways we can do
one-way use for loop iteration
Here is an example
var arr = [11, 2, 3, 7];
var index = 0;
var min = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
index = i;
}
}
console.log(index);
console.log(min);
Output:
1
2
Pass array to Math.min function
Math.min function returns the minimum group of values. It returns a minimum value. The index can be found using Array.indexOf() function.
ES6 example using spread operator:
Here is an example
var minElement = Math.min(...arr);
console.log(minElement);
console.log(arr.indexOf(minElement));
ES5 Example to find the minimum value
var minElement = Math.min.apply(null, arr); //min=1
console.log(minElement);
console.log(arr.indexOf(minElement));
Array.reduce function iterates arrays and reduces the array of elements
var arr = [11, 2, 3, 7];
function minimum(arr) {
let minimumIndex = 0;
arr.reduce((accumulated, current, index) => {
if (current < acc) {
minimumIndex = index;
return current;
} else {
return accumulated;
}
}, Infinity);
console.log(minimumIndex)
console.log(arr[minimumIndex]);
}
minimum(arr);
🧮 Tags
Recent posts
Puppeteer Login Test example How to convert Double to Integer or Integer to double in Dart| Flutter By Example Best ways to fix 504 gateway time out in nodejs Applications Fix for Error No configuration provided for scss Multiple ways to List containers in a Docker with examplesRelated posts