Iterate Through All an Array's Items Using For Loops - Odd splice behavior

Iterate Through All an Array's Items Using For Loops - Odd splice behavior
0

#1

Hey guys, I know there’s an easier/better way to solve this challenge with push(), but I’m curious as to why this particular code is not working (it does on all but one, where it somehow manages to leave some of the nested array’s elements behind). My best guesses lead me to believe it’s because I’m mutating arr’s length during the loop, but I would think this would cause it to skip other ones as well. I’m not sure what caused it to splice part of the nested array and not the other part, when it should spice the entire thing.

Your code so far


function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].indexOf(elem) >= 0) {
         arr.splice(i, 1);
         console.clear();
         console.log(arr);
      }
    }
    newArr = [...arr];
    console.log(newArr);
  // 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.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 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

Using the example call shown above, think about what is happening when i = 0. After the splice, the [3, 2, 3] is removed and arr becomes [ [1, 6, 3], [3, 13, 26], [19, 3, 9]]. At the start of the next iteration, i = 1. The problem is, i needs to be 0, because you need to check the first array [1, 6, 3], but instead the [3, 13, 26] is checked and again spliced out, so after the second iteration, arr becomes [[1, 6, 3], [19,3,9]. At the start of the next iteration, i = 2, but since arr’s length is now 2, the for loop stops based on the condition of i < arr.length no longer being true.

So yes, you are skipping over elements. One easy solution is after every slice, decrement i by 1.

On a side note, why did you write newArr = […arr]? after the for loop? You only needed to return arr. The tests are not actually checking that you did not mutate the array which was passed into the function, so that is why it passes.


#3

Thanks Randell!

I thought I must have been passing over some of them wit that i value, so that makes perfect sense. Thank you clarifying it for me.

As for as the newArr = .[…arr], it was something I was playing with when trying to solve the problem and I didn’t take it out before posting here. I usually try a couple of different approaches if I can think of them. Just me being sloppy :smiley: