Removing specific values from an array

Posted on

Going through Set is a fast and easy way to filter out duplicates from arrays. To filter out specific values instead, we can use a helper function like this one. We can pass it an array of values and a second array of all values we want to remove from the first one.

// 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"
// 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"
Debug
none
Grid overlay