Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript return all indexes of highest values in an array

Tags:

javascript

I'm trying to get the indexes of 'all' the highest values in an array:

[0,1,4,3,4]

Need to get back [2,4] as a result.

Update: Thanks everyone for the quick responses. After reading some of the earlier comments, it spawned this path for me:

var array = [0,1,4,3,4];
var indexes = [];
var highest = Math.max(...array);

array.forEach(function(element, i) {
    if (element == highest) {
        indexes.push(i);
    }
});

I know it's a bit verbose, but it makes sense to me. I better read up on 'reduce'.

like image 427
oprogfrogo Avatar asked Dec 05 '22 10:12

oprogfrogo


1 Answers

Using Math.max you can get the maximum element. Post that you map over the array and get the indices of this max element. The complexity of this approach is O(n);

const arr = [0,1,4,3,4];
const max = Math.max(...arr);
const res = [];
arr.forEach((item, index) => item === max ? res.push(index): null);
console.log(res);
like image 145
Shubham Khatri Avatar answered Feb 23 '23 05:02

Shubham Khatri