My if statement is terminating my for loop too early!

My if statement is terminating my for loop too early!
0

#1

Hello,

This is in reference to: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops

I’m sure my approach here is not the best way to solve this problem. But early termination of the for loop seems like such a fundamental issue, that I feel I must learn how to fix it.

The code is supposed to copy all of the subarrays in arr that DO NOT contain an item matching elem. However, what is happening is the code copies the subarrays until it finds one with a match for elem. That subarray and any that follow it are not copied into newArr.

  let newArr = [];
  // change code below this line
  let add = true;
for (let i=0; i<arr.length; i++) {
  for (let j=0; j<arr[i].length; j++) {
    if (arr[i][j] === elem) {
add = false;
    } 
  }
 if (add == true) {
   newArr.push(arr[i]);
   add = true;
 } 
  }

  // change code above this line
  return newArr;
}

// change code here to test different cases:
console.log(filteredArray([['trumpets', 2], ['flutes', 4], ['saxophones', 2] ], 2));


Thanks and happy coding!

#2

You’re very close. It’s not exiting early. If you put some console.log statements in there, you can see that it is running fine. The problem is the logic.

You have your add variable. I starts out set to true. If a match is found, it gets set to false. Where does it get reset to true? You have:

 if (add == true) {
   newArr.push(arr[i]);
   add = true;
 } 

But, it will only set add to true if it is already true. It never gets reset if add is false. So once add gets set to false, it will always be false. The first one in your test gets excluded so they all do.

One solution would be to move the add = true one line later so it always gets reset and the end of each i loop. Another option would be to get rid of that line and move your let add = true to the first line of the i loop.

A few comments:

The line:

if (add == true)

First of all, === is preferable to == if there is not type conversion needed. And since it is a boolean,

if (add)

is a more standard way to do it.

Also, be sure to properly indent your code. It makes it soooo much easier to follow what is happening. Just make it a habit. It will save you a lot of time and headaches in the long run.


#3

Thank you. I’ve only read the first couple of sentences of your reply. I will add some console.log statements and see if I can work it out from there.

Thanks again!