# Iterate through nested array

Tell us what’s happening:
Describe your issue in detail here.

Why error is coming with this code?
Uncaught TypeError: Cannot read properties of undefined (reading ‘length’)

``````  **Your code so far**
``````
``````
function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
for (let i=0; i<arr.length; i++){
for (let j=0; j<arr[i].length; j++){
if(arr[i][j]===elem){
arr.splice(arr[i],1);
}
else{
newArr.push(arr[i]);
}

}
}
// Only change code above this line
return newArr;
}
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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36`

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

Link to the challenge:

This means you are telling to iterate through the outer array right?
Means if the array length is 4 you have to run the for loop 3 times.

Now consider the question `filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)`

initially i = 0 and length = 4, 0<4 - true - enter loop
arr[0] contains 3 so you are splicing the array so the length of array is not 4 anymore its 3 now.

i = 1, length = 3, 1<3 - true enter loop
arr[0] contains 3 so you are splicing the array so the length will become 2

i = 2, length = 2, 2<2 false exit loop

as you can see you are stopping at index 1 and not iterating the entire array

also check this condition , you are iterating the inner array and you are splicing the outer array every time you meet the given value in the inner array.

syntax of splice is `Array.splice(startIndex,noOfElementsToBeDeleted)`

1 Like

sorry, but I am not getting it.

when arr.splice is executed it cuts out a portion of this array thus its length will be no more stable
eg : if you have array = [ 0 , 1 ]
imagine a for loop looping through this array then for i = 0 and array.length will return 2 and a[0] is cut out using array.splice
the new array will be array = [1]
for i = 1 it will stop since array.length will change (it will decrease by 1) and cause this error

Thank you I got the point.