Kiyana
Kiyana

Reputation: 71

JavaScript For Loop Array Iteration Issue - Using One vs Two Loops

The aim of this problem is to iterate through a list, find the largest value in the list, and then report the index values of the highest values. I was able to solve this problem using two for loops:

var scores = [60, 50, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 44, 18, 41, 53, 55, 61, 51, 44];
var highscore = 0;
var highscoreSolutions = [];

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){
    highscoreSolutions.push(i);
   }
  }

console.log(highscore);
console.log(highscoreSolutions);

I initially tried to solve this problem using just one for loop, but I encountered an initialization issue of sorts, that is, no matter, the first index value would be included in the list of highest scores:

var scores = [60, 50, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 44, 18, 41, 53, 55, 61, 51, 44];
var highscore = 0;
var highscoreSolutions = [];

for (var i = 0; i < scores.length; i++){
  if (scores[i] >= highscore){
    highscore = scores[i];
    highscoreSolutions.push(i);
  } 
}

console.log(highscore);
console.log(highscoreSolutions);

I'm not sure how to get around the issue of adding the 0 index value (without resorting to using two separate for loops). Can anyone help me out? Thanks so much!! :)

Upvotes: 6

Views: 359

Answers (3)

James Brierley
James Brierley

Reputation: 4670

You need to clear the list when you find a new highest value:

var scores = [60, 50, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 44, 18, 41, 53, 55, 61, 51, 44];
var highscore = 0;
var highscoreSolutions = [];
var score;

for (var i = 0; i < scores.length; i++) {
  score = scores[i];
  if (score == highscore) {
    highscore = score;
    highscoreSolutions.push(i);
  } else if (score > highscore) {
    highscore = score;
    // We have a new highest score, so all the values currently in the array
    // need to be removed
    highscoreSolutions = [i];
  }
}

snippet.log(highscore);
snippet.log(highscoreSolutions.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 3

Sean Wessell
Sean Wessell

Reputation: 3510

var scores = [60, 50, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69, 64, 66, 55, 52, 44, 18, 41, 53, 55, 61, 51, 44];

//clone array keeping original as scores, sort the new cloned array, grab the max value
var highscore = scores.slice(0).sort()[scores.length - 1];
var highscoreSolutions = [];

//find occurances of highscore and push to array
for (var i = 0; i < scores.length; i++){
    if (scores[i] == highscore){
        highscoreSolutions.push(i);
    }
}

alert('highscore: ' + highscore + '\nindexes: ' + highscoreSolutions)

You can clone the array using Array.slice(0)

Then run sort() and grab the last value of the new sorted array by checking the length -1

Then iterate the loop to find the indexes where the highscores are.

Upvotes: 0

Dominik Schreiber
Dominik Schreiber

Reputation: 2771

This might sound over-engineered to you, but as you seem to be learning JavaScript I suggest you skip for iterations (well, you should know they exist and they can be used to loop) and learn using JavaScript with the functional programming paradigm (a great interactive tutorial for that) as it leads to more readable and less error-prone code.

A solution to your problem could use [].reduce():

function highest(numbers) {
  return numbers.reduce(function(winner, current, index) {
    if (current > winner.value) {
      return {value: current, indices: [index]};
    } else if (current === winner.value) {
      winner.indices.push(index);
      return winner;
    } else {
      return winner;
    }
  }, {value: Number.NEGATIVE_INFINITY, indices: []});
}

function highest(numbers) {
  return numbers.reduce(function(winner, current, index) {
    if (current > winner.value) {
      return {value: current, indices: [index]};
    } else if (current === winner.value) {
      winner.indices.push(index);
      return winner;
    } else {
      return winner;
    }
  }, {value: Number.NEGATIVE_INFINITY, indices: []});
}

document.querySelector('button').addEventListener('click', function() {
  var randoms = new Array(100).join(' ').split('').map(function() {return Math.ceil(Math.random() * 100)});
  document.querySelector('#array').innerHTML = JSON.stringify(randoms);
  document.querySelector('#result').innerHTML = JSON.stringify(highest(randoms));
});
<button>run</button>
<h3>the array</h3>
<pre id="array"></pre>
<h3>the result</h3>
<pre id="result"></pre>

Upvotes: 1

Related Questions