I need a more optimized version of this javascript code to find the 3 largest values in an array. I need to get the indexes of the largest numbers. Are there any other easier methods to solve the problem?
var maxIndex = new Array();
var maxPoints = new Array();
var scoreByPattern = new Array(93, 17, 56, 91, 98, 33, 9, 38, 55, 78, 29, 81, 60);
function findLargest3() {
maxPoints[0] = 0;
maxPoints[1] = 0;
maxPoints[2] = 0;
for (i = 0; i < scoreByPattern.length; i++) {
if (scoreByPattern[i] > maxPoints[0]) {
maxPoints[0] = scoreByPattern[i];
maxIndex[0] = i;
}
}
for (i = 0; i < scoreByPattern.length; i++) {
if (scoreByPattern[i] > maxPoints[1] && scoreByPattern[i] < maxPoints[0]) {
maxPoints[1] = scoreByPattern[i];
maxIndex[1] = i;
}
}
for (i = 0; i < scoreByPattern.length; i++) {
if (scoreByPattern[i] > maxPoints[2] && scoreByPattern[i] < maxPoints[1]) {
maxPoints[2] = scoreByPattern[i];
maxIndex[2] = i;
}
}
console.log(scoreByPattern + "/******/" + maxPoints[0] + "/" + maxPoints[1] + "/" + maxPoints[2]);
//alert(maxIndex);
}
findLargest3();
Solution Approachif (arr[i] > max) -> max3 = max2, max2 = max , max = arr[i]. else if (arr[i] > max2) -> max3 = max2, max2 = arr[i]. else if (arr[i] > max3) -> max3 = arr[i]. At the end of the loop, we will print all three values.
The best way is to use a combination of sort and slice:
This simple one liner will solve your problem.
[1, -5, 2, 8, 17, 0, -2].sort(function(a, b){return b - a}).slice(0, 3)
So if you have an array and want to find N biggest values:
arr.sort(function(a, b){return b - a}).slice(0, n)
And for N smallest values:
arr.sort(function(a, b){return a - b}).slice(0, n)
Modified version
I have modified my answer to make it more generic. It searches for the indices of the n largest numbers of elements in the array:
var scoreByPattern = [93,255,17,56,91,98,33,9,38,55,78,29,81,60];
function findIndicesOfMax(inp, count) {
var outp = [];
for (var i = 0; i < inp.length; i++) {
outp.push(i); // add index to output array
if (outp.length > count) {
outp.sort(function(a, b) { return inp[b] - inp[a]; }); // descending sort the output array
outp.pop(); // remove the last index (index of smallest element in output array)
}
}
return outp;
}
// show original array
console.log(scoreByPattern);
// get indices of 3 greatest elements
var indices = findIndicesOfMax(scoreByPattern, 3);
console.log(indices);
// show 3 greatest scores
for (var i = 0; i < indices.length; i++)
console.log(scoreByPattern[indices[i]]);
Here is a jsFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With