Bug in Iterate Through All an Array's Items Using For Loops

Bug in Iterate Through All an Array's Items Using For Loops
0.0 0

#1

Tell us what’s happening:
My code so far works for most cases, but it doesn’t work when “elem” exists in every nested array and should result in an empty array. Can someone help me understand why? Thanks!

Your code so far


function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
newArr = [...arr];

for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr[i].length; j++){
    if (arr[i][j]==elem){
      newArr.splice(i,1);
      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 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 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

try adding some console.log statements in each for loop to see if the behaviour is as you expect.


#3

You might want to consider a different approach. Making copy of an array and taking things out from it is very inefficient and more complicated.

What’s wrong with your code is that your newArr gets smaller each time you filter an element. However, you still refer an index from arr, which is longer than newArr. So at some point, the index from arr doesn’t make sense to newArr. For example,

arr = [ [1], [2], [1] ], elem = 1
newArr = [ [1], [2], [1] ]

You are at index 0 of arr and you must remove index 0 of newArr. Now, newArr = [ [2], [1] ]
You are at index 1 of arr, newArr is unchanged.
You are at index 2 of arr, you must remove index 2 of newArr. However, newArr doesn’t have index 2. So, newArr is unchanged.

Your final output is [ [2], [1] ]


#4

Ah, that makes total sense. Thank you!