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'.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With