简体   繁体   中英

Javascript return all indexes of highest values in an array

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

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

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

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

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.

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

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;
}, []);

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) 

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) 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM