Tell us what’s happening:
It deletes the array only if the elem is found just once.
So it works when elem = 19. But not when it needs to iterate again.
It then gives an error:
‘Cannot read property ‘length’ of undefined’
I think in the next iteration it tries to find ‘i’ but it’s not there.
I don’t really understand what is happening.
If someone can explain I would appreciate it.
Your code so far
function filteredArray(arr, elem) {
let newArr = [];
// 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(i--, 1);
newArr = [...arr]
}
}
}
// 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]], 19));
Your browser information:
User Agent is: Chrome/69.0.3497.100
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops