How to find the smallest number and position in JavaScript
- Admin
- Mar 10, 2024
- Typescript Javascript
This tutorial explains different ways to find the smallest number, and index position in an array of elements. There are multiple ways we can do this in Javascript.
Use for loop iteration
- Array always starts from the index with zero, and the minimum value is the first element.
- Assume the first value is the minimum(min = arr[0]) and minimum value index is zero(index=0)
- Iterate the array using for loop with index syntax
- Check current value is the minimum value by comparing the iterated value with the minimum value,
- if true, then assign the min value to the current iterated value, and assign the position to the minimum position.
- if false, then do nothing
- Loop until all elements are iterated.
- Finally, variables(min, index) are minimum values and it’s an index of an array
Here is an example
// Array literal syntax
var arr = [11, 2, 3, 7];
var index = 0;
var min = arr[0];
// Using for loop
for (var i = 1; i < arr.length; i++) {
//Compare the current value with a minimum value
if (arr[i] < min) {
min = arr[i];
index = i;
}
}
// print the value
console.log(index);
console.log(min);
Output:
1
2
Use Math.min() function
Math.min()
function takes the array as a parameter and returns the minimum value in the array
The index
can be found using the Array.indexOf()
function.
The below examples show how to use the Math.min() function using ES6 and ES5 syntax
- 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));
Use Array reduce function
The Array.reduce
function iterates arrays, and applies the function to each element, This function checks if a current value is minimum, and returns a single element.
Array.reduce syntax is Array.reduce(function(accumulated, current, index){})
Accumulated
is a variable to hold the output Current
is the current element Index
is the index of the current element.
var arr = [11, 2, 3, 7];
function minimum(arr) {
let minimumIndex = 0;
// reduces to a single value
arr.reduce((accumulated, current, index) => {
if (current < accumulated) {
minimumIndex = index;
return current;
} else {
return accumulated;
}
}, Infinity);
console.log(minimumIndex);
console.log(arr[minimumIndex]);
}
minimum(arr);
Conclusion
In this tutorial, we learned how to find the smallest number in an array using for loop, Math.min and array reduce function.