removeFromArray javascript exercise


#1

I’m running in to a problem when attempting to remove more than one object from my arrays. I believe the issue is that the for loop needs to basically “reset” every time it removes an item. This causes the for loop to iterate all the way through the array again. Does anyone have any pointers?

var removeFromArray = function(array) {
  let iterate = arguments.length;
  let newArray = Array.from(array);

  for (let i = 1; i < iterate; i++) {
    if (array.includes(arguments[i])) {
      let index = Number(array[i]);
      newArray.splice(index, 1);
    }
  }
  return newArray;
}

#2

Hey @pmbrandvold

The issue here is how you are trying to get the index. You are calling Number(array[i]) which doesn’t return the index position but literally whatever is in the array at that point.

There are ways to get the index although you should also consider what would happen if you had multiple array elements that needed to be removed such as an array of [1,2,2,2,3,4,5] where you wanted to remove all the 2’s.

I’m not sure if this is an exercise and what you are allowed to use but you could consider using the filter method to strip out the values you don’t want https://devdocs.io/javascript/global_objects/array/filter


#3

filter is legal… but most students haven’t encountered it yet at that point

HOWEVER => now’s as good a time as any to learn it


#4

It seems that when I just use i for the splice…

newArray.splice(i, 1);

…it throws an error - it’s off by one. Then, when I change it to i+1, it passes the first test (one object to search for and remove) but it doesn’t work with multiple arguments.

Message:
Expected $.length = 3 to equal 2.
Expected $[1] = 2 to equal 4.
Expected $[2] = 4 to equal undefined.

When I run through the debugger in Chrome dev tools, it looks like the cause behind this is the fact that “i” ends up being off because the array shrinks by one. So I created a newArray but it’s still off for …reasons?.. I’m having trouble tracking it all.

I’m looking into .filter() but it’s definitely taking some time to sift through the documentation and understand it. A part of me wants to work through using splice() so that I can understand what exactly is going wrong with my code, though I’m close to just being done with this! It’s been so frustrating. The code seems so straight forward, but it just never works!


#5

That is because i does not refer to the index of the element to be removed. It refers to the index of the arguments. If it works with +1 then that is simply because you’ve matched up the i with the actual index of the item to be removed by chance.

To be honest that section of the JS course is new so I haven’t done it and I’m not sure how much knowledge is assumed. If I was to try and do it without using any array methods aside from splice I would do an outer loop that iterated over the arguments and then an inner loop that iterated through the array and if it found a match I’d splice it out. One issue with that approach though is generally you shouldn’t iterate through an array and also modify it because when you remove an element from the array it modifies the index position, the only way around that is if you delete an element you also need to set the index position back one so that you don’t skip an element.

Therefore, if I had to write a terrible solution using only loops I’d do something like this.

function loopArray(array) {
  let newArray = Array.from(array);
  for (let i = 1; i < arguments.length; i++) {
    for(let j = 0; j < newArray.length; j++) {
      if(newArray[j] === arguments[i]) {
        newArray.splice(j, 1);
        j--;
      }
    }
  }
  return newArray;
}

Obviously I don’t condone using that approach because it’s really terrible.


#6

This is the first road I went down, but I couldn’t get it to do what I expected and went a different direction pretty quick just because of how I was hammering out ideas quickly. I realize now that the reason it didn’t work the first time, looking back at my original code, is because of a missing bracket -_- so there’s a bunch of time wasted for no reason. Just curious, why is this way terrible? I understand it’s not as clean as using filter, but I’m curious as to why it’s so bad aside from that.


#7

If you modify an array as you iterate it then it messes up the index.

Say you have a for loop iterating an array and you are using that loop as a way to track the index position in the array. If you are currently on index 0, and you delete the first element from the array in that loop then the element that was at index 1 is now at index 0.

Your loop moves onto the next iteration and is pointing to the second element in the array as you’d expect. That means it never checks what is now the first value in the array because it was the second element on the first loop run and the first element in the second loop run.

I’m not sure I explained that well but hopefully you get the idea.


#8

An alternative to using multiple loops (or just ‘manually’ tracking the iterations) would be to use .forEach(). It’s probably not going to win any efficiency awards - as far as I can tell it just recursively goes over the array until there is no action remaining for it to take.

The conversation got me thinking about how the index changes would affect my function.

removeFromArray([1,2,3,4,5,6,7,8,9], 7, 5, 8) was my test.

1st pass: 7 is located at index 6 and .splice’d off. as expected
2nd pass: 5 is located at index 4. again expected, being ‘earlier’ in the array
3rd pass: 8 is located at index 5. we’ve removed 2 elements already!

Didn’t faze the forEach method, so I assume it just goes back to the start of the array each time, until it can iterate over every element without taking action.


#9

I ended up trying the same method as above using loops which passed 2 of the 6 tests. But it was just getting more and more complex and I knew I was doing something wrong.

Thanks for the explanation of why modifying an array while iterating it causes issues.
My code just ended up erasing the whole array.

I had to look at the solution after hours of being stuck and reading up on the JavaScript lessons and googling.