Array related problem

While trying to solve a challenge that reads " Modify the function, using a for loop, to return a filtered version of the passed array such that any array nested within arr containing elem has been removed."

I wrote following code–

function filteredArray(arr, elem) {
  let newArr = [];
  // Only change code below this line
  for (let x =0; x < arr.length; x++){
    for (let y = 0; y < arr[x].length; y++){
      if (arr[x][y]==elem){
        arr.splice(x,1);
      }
    }
    newArr.push(arr[x]);
  }

  // Only change code above this line
  return newArr;
}

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

It generates following error “TypeError: Cannot read property ‘length’ of undefined”

Can you please explain this to me? I am unable to find what’s wrong?

when checking arr[3] and removing it from arr, the inner loop is still checking arr[3] and arr[3].length, but arr[3] is now undefined, it does not have a length property and you get an error

in short: changing the array you are iterating over gives unexpected behaviours, it is highly suggested that you avoid doing that

1 Like

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 it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.