我怎么能找到一个数组的最大值的所有索引在javascript

How can I find all indexes of the max value of an array in javascript?

本文关键字:最大值 索引 javascript 数组 一个 怎么能      更新时间:2023-09-26

我试图找到一种方法来获得数组的最大值,然后找到该值的所有索引。我想再重复两遍。

我有一个8个分数的数组。我要找到所有的第一名,第二名和第三名。

Array = [0, 400, 300, 400, 300, 200, 100, 200]

第一名索引:1,3

第二名索引:2、4

第三名索引:5、7

我如何在javascript中实现这一点?

下面的代码实现了这个功能:

var scores = [0, 400, 300, 400, 300, 200, 100, 200];
// make a working copy, so that we can change the working copy
// while doing the calculations without changing the original array
var working = scores.slice(0),
    max,
    indices,
    numberOfPlaces = 3,
    results = []; 
for (var p = 0; p < numberOfPlaces; p++) {
    max = Math.max.apply(null, working);
    indices = [];
    for (var i = 0; i < working.length; i++)
        if (working[i] === max && working[i] > Number.NEGATIVE_INFINITY) {
            indices.push(i);
            working[i] = Number.NEGATIVE_INFINITY;
        }
    results.push(indices);
}

对于您的输入results将是[[1,3], [2,4], [5,7]]。即results[0]保存第一名索引,results[1]保存第二名索引,以此类推。

如果您后来决定只需要前两个位置,或者想要前五个位置,只需更改numberOfPlaces变量

假设分数不是很大的数字,可以构建一个"分数到索引"的散列,然后按键排序,并打印出索引:

运行示例:

http://jsfiddle.net/nmA35/2/

代码:

var arr = [0, 400, 300, 400, 300, 200, 100, 200];
var hashValueToPosition = {};
var i;
for (i = 0; i < arr.length; i++) {
    hashValueToPosition[arr[i]] = (hashValueToPosition[arr[i]] || []);
    hashValueToPosition[arr[i]].push(i);
}
// see http://stackoverflow.com/questions/208016/how-to-list-the-properties-of-a-javascript-object  for Object.keys or the following:
var getKeys = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}
var arrMaxToMinScores = getKeys(hashValueToPosition).sort().reverse();
for (i = 0; i < arrMaxToMinScores.length; i++) {
    $("body").append("<pre>" + arrMaxToMinScores[i] + ": " + JSON.stringify(hashValueToPosition[arrMaxToMinScores[i]]) + "</pre>");
}
function awardPrizes(arr){
    var L= arr.length, prizes= [[], [], []], n;
    // save the three highest scores in scores array:
    // eg: [400,300,200]
    var scores= arr.slice().filter(function(n, i){
        return arr.indexOf(n)== i;
    }).sort(function(a, b){ return b-a}).slice(0, 3);
    //put the high scoring indexes in the relevant prizes array:
    arr.forEach(function(itm, i){
        n= scores.indexOf(itm);
        if(n!= -1) prizes[n].push(i);
    });
    return prizes;
    //[first group,second group,third group]
}
var data= awardPrizes([0, 400, 300, 400, 300, 200, 100, 200]);

/*  returned value: (Array)
[
    [1, 3],
    [2, 4],
    [5, 7]
]
    */

喜欢函数式编程吗?

a={};[0, 400, 300, 400, 300, 200, 100, 200].forEach(
    (el,i) => a[el]? a[el].push(i) : a[el]=[i]
);
Object.keys(a).sort().reverse().map(k => [Number(k),a[k].sort()])

基本上对所有值进行散列,然后按降序遍历键,以升序提到索引。例:

[
    [400,[1,3]],
    [300,[2,4]],
    [200,[5,7]],
    [100,[6]],
    [0,[0]]
]