我试图找到一种方法来获取数组的最大值,然后找到该值的所有索引。我想再重复两次。
我有一个包含 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);
}
对于您的输入结果
将为[[1,3], [2,4], [5,7]]
。也就是说,results[0]
将保存第一个位置索引,results[1]
将保存第二个位置索引,依此类推。
如果您后来决定只想要前两个位置,或者想要前五个位置,只需更改 numberOfPlaces
变量即可。
关于javascript - 如何在javascript中找到数组最大值的所有索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22289780/