Iterate Through All an Arra's items usin for loops

Iterate Through All an Arra's items usin for loops
0.0 0

#1

Tell us what’s happening:
It’s working for all the inputs except for one

Your code so far


function filteredArray(arr, elem) {
  let newArr = [];
  let arr1=arr;
  for(var i = 0 ; i < arr.length ; i++)
  {
    if(arr[i].includes(elem))
    {
      arr1.splice(i,1)
    }
  }
  for(var j = 0 ; j < arr.length ; j++)
  {
    newArr.push(arr1[j]);
  }
  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/67.0.3396.99 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/


#2

Well, the most glaring problem is this:

  let arr1=arr;

You cannot copy arrays like that. For non-primitive types, you are copying the address, not the data itself. So after this, you still have one nested array, but now you have two variables pointing to it. So, when you slice arr1, you are also slicing arr.

Yes, it’s weird. But it makes sense if you understand how computers store data.

There are ways to truly copy arrays, like slice for ES5 or spread operators for ES6+. But this gets even more complicated because this is a nested array.

But this is besides the point. I think you have the wrong approach. What about, instead of splicing if it is there, what about pushing it onto newArr if it is not there? Then you won’t need the second for loop. (Actually I’m not sure why you need it here, but that’s besides the point.)