Iterate Through All an Array's Items Using For Loops: question about solution

I understand all parts of the solution except for break;. We have previously only used break; in switch cases, and I don’t understand why we want to break out of the loop cycle here. Couldn’t there theoretically be more matches in the array and we would want to keep looking?

Is it because once we’ve found one match in this subarray, we don’t need to keep looking because we already know we’re splicing it out? If THAT’S the answer, what ‘harm’ could come from not break;-ing here? My answer did not pass until I had it, and I never would have solved this without coming to the forums, ha.

That’s fair. I had the same answer as fCC (but forgot the i--;). However, I kept getting this error when I tried running the tests without break;:

// running tests
Cannot read property 'length' of undefined
Cannot read property 'length' of undefined
Cannot read property 'length' of undefined
Cannot read property 'length' of undefined
Cannot read property 'length' of undefined
// tests completed

This happened even after I copy/pasted fCC’s code into my function (minus break;). This is what I have now:

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);
  // 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));

and I keep getting the same error as long as break; isn’t there.

You get that error, because in the first iteration of the inner for loop (i=0, j=0), newArr[0][0] is 3 which is equal to elem (also 3), so you splice out the first sub array [3, 2, 3]. Next you decrease i by one, so now i = -1. Well, when the inner for loop starts again, the for loop condition of j < newArr[i].length is checked. Since i is now -1, this checks j < newArr[-1].length. Array indexes start at zero, so newArr[-1] is undefined and undefined does not have any properties (definitely not one named length), so you get TypeError: Cannot read property 'length' of undefined

1 Like

ahhhhhh understood. okay. Could you maybe throw a comment in the suggestion box to add something that teaches us about breaks before this task?

Thanks for all your help :slight_smile: