最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript return all indexes of highest values in an array - Stack Overflow

programmeradmin4浏览0评论

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

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

Share Improve this question edited Mar 21, 2019 at 16:40 oprogfrogo asked Mar 21, 2019 at 16:14 oprogfrogooprogfrogo 2,0745 gold badges31 silver badges46 bronze badges 10
  • 8 Your efforts so far ? – Code Maniac 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)); – oprogfrogo Commented Mar 21, 2019 at 16:15
  • 1 Why should it renders [2, 4] when the two biggest numbers are 3 and 4 ? – Bambou Commented Mar 21, 2019 at 16:15
  • @KévinHuang this are index numbers for the two 4's in the array – fedesc Commented Mar 21, 2019 at 16:16
  • Oh thanks my bad there ! – Bambou Commented Mar 21, 2019 at 16:16
 |  Show 5 more ments

9 Answers 9

Reset to default 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 plexity 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);

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

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 slightly verbose solution that only iterates once. The idea is that you keep track of the highest value you've seen and pare 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)

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

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 pare with <.

And it's not as plex as I imagined.

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

发布评论

评论列表(0)

  1. 暂无评论