Why do I get "arr[i] is undefined" in my JS nested array?

Viewed 495

I can't figure out why this is not working. I know the issue comes from the 8th line in the condition if(arr[i][j]===elem).

function filteredArray(arr, elem) {
  let newArr = [];

  for (let i = 0; i < arr.length; i++) {

    for(let j = 0; j < arr[i].length; j++) {

      if(arr[i][j]===elem) {

        newArr.push(arr.splice(i,1));

      }
    }
  }
  return newArr;
}

if I enter in my console a test like :

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

I get the error arr[i] is undefined.

1 Answers

Your problem is that you are modifying the length of your array inside your loop. You have arr.splice(i,1) on the inside of your loop; every time that gets called, your array shortens by 1. Eventually, your array gets too short, and you attempt to read an item out of bounds. You can prove this by commenting out that line inside the if block; your code will run without errors.

I'm not sure exactly what values you're trying to put in newArr, but there's no reason to modify arr to get your values. Just read the value you want from arr, and push it to newArr, and you'll have no problems.


As an aside, is there any reason you have to use for loops vs. using native array methods like arr.filter()?

Related