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
Selected Reading
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.
Example
The code for this will be −
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
And the output in the console will be −
[ 0, 3, 5 ]
Advertisements
