Why don't you just sort it and move the first (or last, if sorted ascending) three elements.
var maxPoints = new Array(); var scoreByPattern = new Array(93,17,56,91,98,33,9,38,55,78,29,81,60); scoreByPattern.sort(); maxPoints[0] = scoreByPattern[scoreByPattern.length - 1]; maxPoints[1] = scoreByPattern[scoreByPattern.length - 2]; maxPoints[2] = scoreByPattern[scoreByPattern.length - 3];
Edit
If you need the indices of the largest arrays, you can create a copy that you sort, and then find the indices in the original array:
var scoreByPattern = new Array(93,17,56,91,98,33,9,38,55,78,29,81,60); // Make a copy of the original array. var maxPoints = scoreByPattern.slice(); // Sort in descending order. maxPoints.sort(function(a, b) { if (a < b) { return 1; } else if (a == b) { return 0; } else { return -1; } }); // Find the indices of the three largest elements in the original array. var maxPointsIndices = new Array(); maxPointsIndices[0] = scoreByPattern.indexOf(maxPoints[0]); maxPointsIndices[1] = scoreByPattern.indexOf(maxPoints[1]); maxPointsIndices[2] = scoreByPattern.indexOf(maxPoints[2]);
Another approach for finding indexes without sorting is as follows:
var scoreByPattern = new Array(93,17,56,91,98,33,9,38,55,78,29,81,60); var maxIndices = new Array(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE); for (var i = 0; i < scoreByPattern.length; i++) { if (maxIndices[0] < scoreByPattern[i]) { maxIndices[2] = maxIndices[1]; maxIndices[1] = maxIndices[0]; maxIndices[0] = scoreByPattern[i]; } else if (maxIndices[1] < scoreByPattern[i]) { maxIndices[2] = maxIndices[1]; maxIndices[1] = scoreByPattern[i]; } else if (maxIndices[2] < scoreByPattern[i]) maxIndices[2] = scoreByPattern[i]; }