Tell us what’s happening:
In the line j===arr[i].length, length is not defined. What’s the reason and is there a way around it in the existing code?
Your code so far
function filteredArray(arr, elem) {
let newArr = [];
let j =0;
// change code below this line
for(let i=0;i<arr.length;i++){
for(j=0;j<arr[i].length;j++){
if(arr[i][j]===elem){
arr.splice(i,1);
break;
}
}
if(j===arr[i].length){
newArr.push(arr[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/69.0.3497.100 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
Gigusek
2
It’s not length that’s not defined. It can’t read the length OF undefined.
The problem is on the line 12 and 13, you’re using [i] outside of the for loop scope.
The [i] is in the scope of for loop for i. Also globally declaring i doesn’t seem to work.
Gigusek
4
Whoops, my bad.
Well, I don’t know. I’ve checked the code for errors in different parts of the function and got none, but only an empty array is returned.
camper
5
@nimrodcoder There are a few problems with this code. I suggest starting with let j =0;
. Why did you add this?
Removing this gives me the error: j is undefined
. Isn’t it defined in your nested for loop the same way i
is? It’s not, so you can fix that.
Then, as you try to fix the code from there, pay attention to scoping as j
will only be accessible from within the nested for loop.
I think you’ll be able to complete it once this structure is in place.
I looks to me that you are looping over arr while removing elements. What does that do to your index? arr.length?
Do you really need to remove these from arr?
1 Like
snigo
7
@nimrodcoder, this might make your life easier with this assignment:
Cheers
1 Like
This solved it!!! thanks! i only needed to remove the splice line.
see…the first reply suggested scoping problems, that’s when i declared them globally. Scoping wasn’t as issue tho.