Tell us what’s happening:
My thought process making this code: I nested a for loop inside a for loop to look through the nested array. If the elem is an element of a nested array, the whole nested array is deleted. Note that I set the newArray to copy the arr, so I could delete the nested arrays directly.
When I try to run the code I get the error message: “Cannot read property ‘1’ of undefined”.
I have checked the code for any spelling mistakes, misplaced curly brackets or parenthesis, but I could not find any errors. Is the delete newArr[i]; a valid line of code? Would that delete the whole array, or would it just “clear” it, so it would be like this []?
I would appreciate it if you could give an explanation as to why this does not work, and how to fix it.
*Your code so far
function filteredArray(arr, elem) {
var newArr = [];
// change code below this line
newArr = [...arr];
for (var i = 0; i < arr.length; i++){
for(var x = 0; x < arr[i].length; x++){
if (elem == newArr[i][x]){
delete newArr[i];
}
}
}
// 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]], 3));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
.
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