FCC Iterate Through All an Array's Items Using For Loops

Hello, there!
I was trying to solve this fcc’s challenge with nested for and splice, but something is going wrong and I can’t find the error…

Here’s my code:

function filteredArray(arr, elem) {
        let newArr = [];
        for (var i = 0; i < arr.length; i++) {
          for (var j = 0; j < arr[i].length; j++) {
            if (arr[i][j] == elem) {
              arr.splice(i, 1);
              j = 0;
              i = 0;
              break;
            }
          }
        }
        return arr;
      }

The thing is when I use break inside the last for I go to the upper for, correct? I was trying to zero the var i and j because arr is being changed on runtime but it isn’t working…
If I try

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

all subarrays except [1,6,3] will be deleted.

consider what happens. the break stop the loop, then it go to the external i loop. the i loop has finished an iteration and go: i++.
so the new element at the zero index is never checked.

So how could I force the loop to start from 0 after a break ?

what’s determining the value of i after the splice?

I don’t know if this is recommended, but I did this:

for (var i = 0; i < arr.length; i++) {
          for (var j = 0; j < arr[i].length; j++) {
            if (arr[i][j] == elem) {
              arr.splice(i, 1);
              i = -1;
              break;
            }
          }
        }

other thing, if the first three elements in the array are fine, and the fourth is to be removed, after that do you need to start checking again at index 0?

It was just a quick fix, but indeed it’s not the most efficient code :slight_smile:
Thx for the insight ieahleen

I think:

for (var j = 0; j < arr[i].length; j++) {
            if (arr[i][j] == elem) {
              arr.splice(i, 1);
              i--;
              break;
            }

Work better… agree?

there is no unnecessary starting from the start. yes, it works better!

1 Like