-2

So I'm writing a code that puts the highest score into a new array and i don't want to use the push function. Please take a look at my code, i really dont know what to put in bestSolutions[?] as i would like it to be a new array containing the index of the highestScores.

var scores = [60,50,60,58,54,54,58,50,52,54,48,69,34,55,51,52,44,51,69,64,66,55,52,61,46,31,57,52,44,18,41,53,55,61,51,44];
var bestSolutions = [];
var highScore = 0;
var j = 0
for (var i = 0; i < scores.length; i++){
    if (scores[i] > highScore){
        highScore = scores[i];
    }

}

for (var i = 0; i < scores.length; i++){
    if (scores[i] == highScore){
        bestSolutions[] = i
    }

}
console.log(bestSolutions)
console.log(highScore);

3 Answers3

0

You could use unshift():

bestSolutions.unshift(i);

You could alternatively just explicitly set the index:

bestSolutions[0] = i;
esqew
  • 42,425
  • 27
  • 92
  • 132
0

var scores = [60,50,60,58,54,54,58,50,52,54,48,69,34,55,51,52,44,51,69,64,66,55,52,61,46,31,57,52,44,18,41,53,55,61,51,44];
var bestSolutions = [];
var highScore = 0;
var j = 0
for (var i = 0; i < scores.length; i++){
    if (scores[i] > highScore){
        highScore = scores[i];
    }

}

for (var i = 0; i < scores.length; i++){
    if (scores[i] == highScore){
        bestSolutions[bestSolutions.length] = i //Here the change
    }

}
console.log(bestSolutions)
console.log(highScore);
takrishna
  • 4,884
  • 3
  • 18
  • 35
0

You could just set the last index + 1, which is fortunately the arrays length:

 bestSolutions[bestSolutions.length] = i;

Given that .push does exactly that, I don't see a reason why you want to avoid it.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151