The following code does the trick:
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);
}
For your input results
will be [[1,3], [2,4], [5,7]]
. That is, results[0]
will hold the first place indices, results[1]
will hold the second place indices, and so on.
If you later decided you only wanted the first two places, or your wanted the first five, just change the numberOfPlaces
variable.