Can someone tell me why my code isn't working?

My idea behind this is that we iterate through each index of the nested arrays. and if the elem is present in the nested arrays we keep the newArr as is but if its not we push nested arrays inside the newArr. the console returns **newArr = [19, 3, 9] ** when3 is elem. I’d appreciate some feedback. Thanks!


function filteredArray(arr, elem) {
let newArr = [];

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

  if (arr[i][j] !== elem) {
    newArr = [...arr[i]];
  } else if (arr[i][j] === elem) {
    newArr = newArr;
  }

  }
}
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/87.0.4280.88 Safari/537.36.

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

Link to the challenge:

two things, you need to decide if the array is good or not after looking at all of it, not first item
also newArray = [...arr[i]] will overwrite newArray each time

1 Like

okay thanks so much. i get it now.