HELP! Iterate Through All an Array's Items Using For Loops

Tell us what’s happening:
What is wrong with my logic?

Your code so far


function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
for(i=0; i<arr.length; i++){
  if(arr[i].indexOf(elem) >=0){
    delete arr;
  }else{
    return newArr;
  }
}
  // 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 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 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/

You aren’t changing newArr anywhere in your function so your function always returns [ ]

delete is not doing what you think
You can do this delete arr[i] but not this delete arr. delete only works on object properties
Even if you did delete an element there will be a ‘hole’ at that index. The array does not resize to cover the hole.

const array = [1,2,3,4];
delete array[1];
console.log(array);  // [ 1, <1 empty item>, 3, 4 ]

You could use .splice() to remove an element. That would not leave a hole but there are issues with that too.

Removing elements from an array while you are iterating over it can be messy. You are changing the indexes of the following elements when you remove one. Usually when you do this elements get skipped over.


You should probably leave the array passed as an argument intact and fill the newArr with the elements you want to keep and then return newArr

function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
for(i=0; i<arr.length; i++){
  if(arr[i].indexOf(elem) >=0){
    delete arr;  // delete only works on object properties, not entire object, also it leaves a hole at that index
  }else{
    return newArr;  // this would halt function and return whatever was in newArray
  }
}
  // change code above this line
  return newArr;  // you haven't added anything to newArr so this will always return []
}

// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

Understood! Thank you so much!!