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
Return indexes of greatest values in an array in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers. The array may contain more than one greatest element (i.e., repeating greatest element).
We are required to write a JavaScript function that takes in one such array and returns all the indices of the greatest element.
Using Array.reduce() Method
This approach first finds the maximum value using Math.max(), then uses reduce() to collect all indices where the element equals the maximum value.
const arr = [10, 5, 4, 10, 5, 10, 6];
const findGreatestIndices = arr => {
const val = Math.max(...arr);
const greatest = arr.reduce((indexes, element, index) => {
if(element === val){
return indexes.concat([index]);
} else {
return indexes;
};
}, []);
return greatest;
}
console.log(findGreatestIndices(arr));
Output
[ 0, 3, 5 ]
Using for Loop Method
A simpler approach using a traditional for loop to find the maximum value and collect indices in two passes:
const arr = [10, 5, 4, 10, 5, 10, 6];
const findGreatestIndicesLoop = arr => {
const maxVal = Math.max(...arr);
const indices = [];
for(let i = 0; i < arr.length; i++){
if(arr[i] === maxVal){
indices.push(i);
}
}
return indices;
}
console.log(findGreatestIndicesLoop(arr));
[ 0, 3, 5 ]
Using Array.map() and filter() Method
This functional approach maps each element to its index if it equals the maximum, then filters out undefined values:
const arr = [10, 5, 4, 10, 5, 10, 6];
const findGreatestIndicesMap = arr => {
const maxVal = Math.max(...arr);
return arr.map((element, index) => element === maxVal ? index : undefined)
.filter(index => index !== undefined);
}
console.log(findGreatestIndicesMap(arr));
[ 0, 3, 5 ]
Comparison
| Method | Readability | Performance | Memory Usage |
|---|---|---|---|
| Array.reduce() | Moderate | Good | Low |
| For Loop | High | Best | Low |
| Map & Filter | High | Moderate | Higher |
Conclusion
All three methods effectively find indices of maximum values. The for loop approach offers the best performance, while the functional methods provide cleaner, more readable code for most use cases.
