I have an array and I'm trying to get two of the highest values of the array, for example:
[1, 2, 3, 4, 3, 1, 0]
I need the return to be like this: [ 4, 3]
How can this be done? At the moment I have a function that returns me the max of the array only, (in this example, only [4]). But I need the highest and the second, if it repeats, like this example (3 appears two times), only one of them, to make an array of two elements.
My function at the moment:
indexOfMax(arr) {
var max = -Infinity;
var maxIndices = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] === max) {
maxIndices.push(i);
} else if (arr[i] > max) {
maxIndices = [i];
max = arr[i];
}
}
return maxIndices;
},
Thanks for all the answers! You guys rock!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…