Two For Loops (Question on i--)

Two For Loops (Question on i--)
0

#1

Tell us what’s happening:
Why do I need the i-- after the if statement?
Is it because if the array is removed, all of the other items in array get moved down (-1) in the array index?

Your code so far


function filteredArray(arr, elem) {
  let newArr = [...arr];
  // change code below this line
  for (let i = 0; i < newArr.length; i++) {
    for(let j = 0; j < newArr[i].length; j++) {
      if (newArr[i][j] === elem) {
        newArr.splice(i,1);
        i--;
        break;
      } 
    }
  }
  // change code above this line
  return newArr;
}

// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops/


#2

Whenever you do something like add something or remove something to an array inside the for loop and are using the length of that same array to determine when it ends unless you are compensating in some way for the change in length you can (especially where you keep adding!! something to it) get caught up in endless loops…

I usually (I know it’s an extra step but) clone the initial array and change it’s clone based on iterating through the original array…

{Edit}: clone your array!!


#3

You shouldn’t be changing the code above “change code below this line”. Rather than dumping arr into newArr and then mutating the array you are iterating over (which is a bad idea, and why the i-- is required), look at the example code in the challenge and observe that the new array is constructed in the loops.


#4

originally I had this but I got lost on what to put in the if (arr[i][j] == elem), and what to do after

function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
  for (let i = 0; i < arr.length; i++) {
    for(let j = 0; j < arr[i].length; j++) {
      if (arr[i][j] == elem) {
        
      } else {
        newArr.push(arr[i]);
      }
    }
  }
  // change code above this line
  return newArr;
}

// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

#5

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

Note: Backticks are not single quotes.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.