Skip to content
Advertisement

Loop to remove an element in array with multiple occurrences

I want to remove an element in an array with multiple occurrences with a function.

JavaScript
JavaScript
JavaScript

This loop doesn’t remove the element when it repeats twice in sequence, only removes one of them.

Why?

Advertisement

Answer

You have a built in function called filter that filters an array based on a predicate (a condition).

It doesn’t alter the original array but returns a new filtered one.

JavaScript

You can extract it to a function:

JavaScript

However, the original filter seems expressive enough.

Here is a link to its documentation

Your original function has a few issues:

  • It iterates the array using a for... in loop which has no guarantee on the iteration order. Also, don’t use it to iterate through arrays – prefer a normal for... loop or a .forEach
  • You’re iterating an array with an off-by-one error so you’re skipping on the next item since you’re both removing the element and progressing the array.
Advertisement