Can someone explain what's wrong with my code?

This is the problem -

" We have defined a function, filteredArray , which takes arr , a nested array, and elem as arguments, and returns a new array. elem represents an element that may or may not be present on one or more of the arrays nested within arr . Modify the function, using a for loop, to return a filtered version of the passed array such that any array nested within arr containing elem has been removed. "

This is my code -


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

console.log(filteredArray([[3, 2, 3], [3, 13, 26], [1, 6, 3], [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/92.0.4515.159 Safari/537.36

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

Link to the challenge:

What are you having trouble with? What do the failing tests say?

so here we see both a reason for not mutating input, and a reason for not messing with array length within a for that is incrementing array indices.

Your for loop is incrementing i no matter what at the end of each iteration. However your if condition says there will be cases where you eliminate a nested array from arr itself. Therefore the following situation is inevitable:

[arr0,arr1,arr2] as input, going through your for loop with i=0 and arr0 meets the condition for splicing, at the end of the for loop your input is now:
[arr1,arr2] with i=1.
So the second iteration of the for loop is now checking arr2, having skipped arr1 entirely.

Easiest way to avoid this is to have a separate array to push elements into.

2 Likes

Yoo
Thanks a lot!
This makes sense.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.