4

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'.

10
  • 8
    Your efforts so far ? Commented Mar 21, 2019 at 16:14
  • I've used this, but I only get back one value out of it: arr.indexOf(Math.max(...arr)); Commented Mar 21, 2019 at 16:15
  • 1
    Why should it renders [2, 4] when the two biggest numbers are 3 and 4 ? Commented Mar 21, 2019 at 16:15
  • @KévinHuang this are index numbers for the two 4's in the array Commented Mar 21, 2019 at 16:16
  • Oh thanks my bad there ! Commented Mar 21, 2019 at 16:16

9 Answers 9

4

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);

Sign up to request clarification or add additional context in comments.

Comments

4

Here idea is

  • First find the max value using math.max
  • Now loop through the array and add the index if the value is same as max

let arr = [0,1,4,3,4]
let max = Math.max(...arr)

let op = []
for(let i=0; i<arr.length; i++){ 
 if(arr[i] === max){
    op.push(i)
  }
}
console.log(op)

One alternate way of doing is using reduce and a variable to keep track of max value and than access the max key's value

let arr = [0,1,4,3,4]
let max = null

let op = arr.reduce((op,inp,index)=>{
   op[inp] = op[inp] || []
   op[inp].push(index)
   if(inp > max){
    max = inp
   }
   return op
},{})
console.log(op[max])

Comments

2

Find the max value with reduce first, then find the indexes:

var arr = [0,1,4,3,4];

var max = arr.reduce((acc,curr) => curr > acc ? curr : acc);
var res = arr.reduce((acc,curr,idx) => curr === max ? [...acc, idx] : acc, []);

console.log(res);

1 Comment

it fails for arr = [-5]
1

Here's a slightly verbose solution that only iterates once. The idea is that you keep track of the highest value you've seen and compare against it.

let arr = [0,1,4,3,4];
let maxValue = arr[0];
let maxIndexes = [];

arr.forEach((val, index) => {
  if(maxValue === val){
    maxIndexes.push(index);
  }

  if(maxValue < val){
    maxValue = val;
    maxIndexes = [index];
  }
})

console.log(maxIndexes);

Comments

1

Simply, Find the max value

var max_val = Math.max.apply(null, array)

Then use reduce function

var max_val_indexes = arr.reduce(function(arr, ele, i) {
    if(ele === max_val)
        arr.push(i);
    return arr;
}, []);

Comments

1

To achieve expected result, use below option

  1. Looping through using map
  2. Capturing max index value
  3. Filtering out max index values

var arr = [0,1,4,3,4]

const maxIndex = arr
  .map((v, i, self) => v === Math.max(...self) ? i : -1)
  .filter(index => index !== -1);

console.log(maxIndex)

Comments

1

There's no reason to find the max value and then loop again through the array. You can just keep track of the current max value as you traverse the array once:

let arr =  [0,1,4,3,4]

let maxIndexes = arr.reduce((maxes, n, i, a) => {
    let cur = a[maxes[0]]  // current max value
    if (cur == undefined || n > cur) return [i]
    return (cur == n) ? maxes.concat(i) : maxes
}, [])


console.log(maxIndexes)

Comments

1

Here's a fairly simple version. Once you have the maximum value, iterate over the list testing each one for a match, adding it's index if it's equal:

const allMax = (xs, max = Math.max(...xs)) => 
  xs.reduce((all, x, i) => x == max ? [...all, i] : all, [])

console.log(allMax([0, 1, 4, 3, 4]))

You could fix this up to run in a single pass (skipping the Math.max call) but the code would be more complex.

Update

This is that second version I mentioned:

const allMax = (xs) => xs.reduce(
  (a, x, i) => x > xs[a[0]] ? [i] : x < xs[a[0]] ? [...a] : [...a, i],
  [0]                                
)

console.log(allMax([0, 1, 4, 3, 4]))

This does everything in one pass. It will return [0] if you supply an empty list, which might be a problem, but it's hard to know what to do with it. One advantage is that it will work on other sorts of input. allMax(['a', 'b', 'd', 'c', 'd']) //=> [2, 4]. Dates should also work or anything you can compare with <.

And it's not as complex as I imagined.

Comments

0

you can get two array one if the duplicate maxim and another is the indexof the maxim number. please check the below code it might help you bro

let a = [1,3,6,6]
Math.max.apply( Math, a );
let index =[];
let y=0;
let maxValue = a.reduce( function (value,obj){
  if(Math.max.apply( Math, a) == obj){
    	index.push(y);
 		 	value.push(obj);
  }
  ++y;
  return value;
},[]);

console.log(maxValue);
console.log(index);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.