LeetCode problem #27 — Remove Element (JavaScript)

Duncan McArdle
2 min readDec 17, 2020

In this LeetCode problem, we’re asked to remove an element from a provided array, and to do so in-place. This is very similar to the previous challenge, and indeed the solution is very similar too.

Solution #1: Loop

In this solution, we loop through the numbers contained within the provided array, whilst checking each to see if it matches the number being removed. Whilst doing this, we also maintain a counter (j in the code), which tells us where in the original array we should place the next value.

The way this works is that if we start with an array of [1, 2, 3] and want to remove all occurrences of 2, we will look at 1, see that it is not being removed, and thus place it at the counter’s current value (which will be 0 to start with), leaving the array unchanged. We’ll then look at 2, which we see does need to be removed, and so we move onto the next number without incrementing the counter. Finally when we reach 3, we see that it is not being removed, and so we place it at the counter’s position in the array (the counter is still set to 1 at this point), and increment the counter, giving us an array of [1, 3, 3] and a counter value of 2. This then allows us to chop the array at the counter’s position, giving us a final array of [1, 3].

Like with the previous exercise, LeetCode doesn’t require us to chop off the surplus data, so I have left the line to do so in, but commented it out. In addition, LeetCode ask that we return the length of the new array, rather than the array itself, as it is being edited by reference.

Solution #2: .filter()

Although not an accepted answer by LeetCode, I’d be remiss if I didn’t mention by far the simplest method of obtaining the desired result: .filter(). This method returns the filtered version of an array, and allows you to specify said filter using an arrow function, which makes for an incredibly neat solution:

--

--

Duncan McArdle

Full-stack software developer from the UK, author of the Aftermath book series, full time tech-nerd.