简体   繁体   English

Javascript返回数组中最高值的所有索引

[英]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: 我试图让' all '的索引成为数组中的最高值:

[0,1,4,3,4]

Need to get back [2,4] as a result. 结果需要取回[2,4]

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 首先使用math.max找到最大值
  • Now loop through the array and add the index if the value is same as max 现在循环遍历数组并添加索引(如果值与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 另一种方法是使用reduce和变量来跟踪最大值,然后访问max key的值

 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. 使用Math.max可以获得最大元素。 Post that you map over the array and get the indices of this max element. 发布您在数组上映射并获取此max元素的索引。 The complexity of this approach is O(n) ; 这种方法的复杂性是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: 首先使用reduce查找最大值,然后找到索引:

 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. 你可以解决这个问题,一次运行(跳过Math.max调用),但代码会更复杂。

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. 如果你提供一个空列表,它将返回[0] ,这可能是一个问题,但很难知道如何处理它。 One advantage is that it will work on other sorts of input. 一个优点是它可以用于其他类型的输入。 allMax(['a', 'b', 'd', 'c', 'd']) //=> [2, 4] . 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 然后使用reduce函数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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