Basic Data Structures: Iterate Through All an Array's Items Using For Loops

Trying to solve this, can someone tell me why and where im going wrong

`function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
for (let i = 0; i < arr.length; i++) {
  if (arr[i].indexOf(elem) === -1) {
    newArr = [...arr[i]];
  }
}
  // change code above this line
  return newArr;
}

// change code here to test different cases:
console.log(filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18));`

However if i change the spread operator line to newArr.push([…arr[i]]);
it works. i think im not understanding spread properly maybe.

This line overwrites newArr each iteration, so the elements that were present at the end of the previous iteration are no longer there after you execute this line each time.

3 Likes

you should use this syntax
for(let i=0;i<arr.length;i++){
if(arr[i].indexOf(elem)==-1){
newArr.push([…arr[i]]);
}
}

You can use the code below too:

for (let i=0; i<arr.length; i++){
      if (arr[i].indexOf(elem)===-1){
      //now start forming a new array for those without elem
      newArr.push(arr[i]);
      }
  }

That works.

3 Likes