What is wrong with this solution?

Basic Data Structures: Iterate Through All an Array’s Items Using For LoopsPassed

So while working on this challenge I decided to come up with a different solution for it. But for some reason it does not work, I understand the solution that appears in the help section but I would like to know what part of my logic is wrong. I am filling the “newArr” with all the objects inside “arr” and then eliminating the ones that contain the “elem” as I iterate through it.

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

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

According to my logic console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)); should outcome “” but instead returns “[ [ 1, 6, 3 ], [ 19, 3, 9 ] ]”.

Hello~!

You are using .splice inside of a for loop that iterates through the array. Your array length is changing as the loop runs. Try putting a console.log(i) as the first line of your for loop and see what prints to the console. :slight_smile:

2 Likes

Awesome, I see it! @nhcarrigan
Now, I tried to fix it, this is what I did, although still doesn’t give me the right outcome.

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

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

Okay, here you splice out the sub-array if it contains the element you’re looking for. However, because this is still in a loop, and is based on the iteration variable, things get wonky again. Let’s look at your loop iteration:

//for iteration 0:
newArr: [[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]]
arr[0]: [3, 2, 3] //has the 3 element
newArr.splice(0, 1) // removes [3, 2, 3] woohoo!

//for iteration 1:
newArr: [[1, 6, 3], [3, 13, 26], [19, 3, 9]]
arr[1]: [1, 6, 3] //has the 3 element
newArr.splice(1, 1) //removes [3, 13, 26] hmmmm

//for iteration 2:
newArr: [[1, 6, 3], [19, 3, 9]]
arr[2]: [3, 13, 26] //has the 3 element
newArr.splice(2, 1) //removes nothing because newArr doesn't have an index of 2!

See how the splice is still affecting your iteration?

I think NOW I see it haha! So is kind of the same issue you mention before right. So because I modified newArr, by removing [3, 2, 3], newArr[1] != [1, 6, 3] , now actually newArr[1] =[3, 13, 26], and since two arrays have been erased there is no newArr[2] anymore!
I just want to make sure I actually understood what’s going on!
Thank you so much for your help!!!

1 Like