LeetCode problem #27 — Remove Element (JavaScript)

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

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()

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Duncan McArdle

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