TypeError: Cannot read property 'length' of undefined in nested for loop

function argument arr in line 4 and 5 is undefined. But why?
Considering that arr.length in line 3 is just fine.
my code so far


function filteredArray(arr, elem) {
let newArr = [];
for(var i = 0; i < arr.length; i++){
  for(var j = 0; j < arr[i].length; j++){
    if (arr[i][j] == elem){
      arr.shift()
    }
  }
}
return newArr;
}

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

Challenge: Iterate Through All an Array’s Items Using For Loops

Link to the challenge:

1 Like

Try creating a separate array and adding the values you need to it.

I see that you have provided no arguments for this.
And one more thing I noticed that you created a variable newArr and returned it. But never modified it. So the newArr would be equal to an empty array

Could you please elaborate a little

What are you expecting would happen with this code. Explain line by line

Thanks for spotting the unmodified newArr.
I’ve made corrections.

.shift() takes no argument

Cool! let us know if you pass that challenge

arr in these 2 lines is still undefined. I don’t understand why?

if you have modified your code, share it again…

Ignore this post…

Wait a sec…no need to add arguments to shift()

My code currently:

function filteredArray(arr, elem) {

  let newArr = [];

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

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

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

        arr.shift()

      }

    }

  }

  newArr = arr

  return newArr;

}

You should cross-check, based on what I know shift() removes the first item of an array

instead of arr.shift() maybe try using the arr.splice() method

I just read the challenge…It says you to store the updated elements to the newArr so removing the element will be of no use. Instead tru pushing the values to the new array

Oh my god…I am really sorry. I confused you…I didnt read it properly.

It’s okay.
Thanks a lot for trying.
The problem isn’t with the .shift() Its in lines 3 and 5

Actually the problem IS with shift() as it deletes the first element of the array, where you’re actual goal is to remove the index at which the element exists.

You’ll learn better way to do this in future lessons, but for now you can create a newArr and add the arrays that DONT contain the given elem.

Hint: if the current array does NOT contain elem, add it to the new Array, thus ending up with an array that has those arrays removed.

lol sorry mods

2 Likes

I’ve solved it :sweat_smile:

I used indexOf() to check for elem and push() to add it to newArr, Worked nicely

Thanks a lot.

1 Like