How to find the smallest number and position in JavaScript
- Admin
- Sep 20, 2023
- Typescript Javascript
This tutorial explains different ways to find the smallest number in an array of elements.
Find the smallest number and position in the array of javascript
There are multiple ways we can do
-
one-way use for loop iteration
- Assume, the index is zero and the minimum value is the first element
- Iterate the array and check current value is the minimum value, if found assign the min value to the current value and position to the minimum position
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
- using Math.min function
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));
- using Array reduce function
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);