Removing specific values from an array

Going through Set is cool to filter out duplicates. If you need to filter out specific values instead, you can use this helper.

// takes an array of values and a second array of values to take out of it
const without = (array, valuesToRemove) => {
  return array.filter(value => !valuesToRemove.includes(value))
}

// all instances of the values to filter out will be removed
without([0, 8, 12, 15, 4, 8, 15, 23], [8, 15])        // ⇒ [0, 12, 4, 23]

// using `.split()` and `.join()`, we can quickly filter values from strings
without('↑↑↓↓←→←→BA'.split(''), ['←', '↑']).join('')  // ⇒ '↓↓→→BA'

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.