Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find indexes of multiple minimum value in an array in JavaScript
Suppose we have an array of numbers like this −
const arr = [1,2,3,4,1,7,8,9,1];
Suppose we want to find the index of the smallest element in the array i.e. 1 above.
For this, we can simply use −
const min = Math.min.apply(Math, arr); const ind = arr.indexOf(min);
The above code will successfully set ind to 0, which indeed is correct.
But what we want to achieve is that if there are more than one minimum elements in the array, like in the above array (three 1s), then we should return an array containing all the indices of minimum elements.
So, for this array, our desired output is the following i.e. three 1s found at index 0, 4, and 8 −
const ind = [0, 4, 8]
We are required to write a JavaScript function that takes in an array of numbers and returns an array of all the indices of minimum elements in the array.
Using reduce() and for loop
The following approach first finds the minimum value using reduce(), then iterates through the array to collect all indices where the minimum value occurs:
const arr = [1,2,3,4,1,7,8,9,1];
const minArray = arr => {
const min = arr.reduce((acc, val) => Math.min(acc, val), Infinity);
const res = [];
for(let i = 0; i
[ 0, 4, 8 ]
Using Math.min() and filter()
A more concise approach using Math.min() to find the minimum value and filter() with map() to get indices:
const arr = [1,2,3,4,1,7,8,9,1];
const findMinIndices = arr => {
const min = Math.min(...arr);
return arr
.map((value, index) => value === min ? index : -1)
.filter(index => index !== -1);
};
console.log(findMinIndices(arr));
[ 0, 4, 8 ]
Using forEach() Method
Another approach using forEach() for a single pass through the array:
const arr = [1,2,3,4,1,7,8,9,1];
const getMinIndices = arr => {
const min = Math.min(...arr);
const indices = [];
arr.forEach((value, index) => {
if (value === min) {
indices.push(index);
}
});
return indices;
};
console.log(getMinIndices(arr));
[ 0, 4, 8 ]
Comparison
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| reduce() + for loop | Good | Good | Medium |
| Math.min() + filter() | Excellent | Good | Short |
| forEach() | Excellent | Good | Medium |
Conclusion
All three methods effectively find indices of minimum values in an array. The Math.min() with filter() approach offers the most concise solution, while forEach() provides excellent readability for developers preferring imperative style.
