LeetCode problem #27 — Remove Element (JavaScript)

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.

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:

--

--

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

Duncan McArdle

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