Problem Iterate Through All an Array's Items Using For Loops

Tell us what’s happening:
Hello,

Why the code is still in a error?

Thanks.

Your code so far


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

  return newArr;  
}

// change code here to test different cases:
console.log(filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")); 

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 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

Using delete on an array will create an empty array element. I recommend not trying to use delete. That is best used for objects when you want to remove a property. If you want to remove an array element, look into using Array.prototype.splice, though this challenge can be solved other ways without splice.

Why not start with newArr being an empty array and then iterate through arr and push the relevant arr elements to newArr? This means you would only push the arr element if it does not contain elem.

1 Like

Thanks Randellawson.

Yes, you are right, your solution is better with push()