Removing the First Instance of an Element from a ES6 JavaScript Array

To build upon Marius Schulz‘s approaches to removing from an array, if you want to remove the first instance of an element in an array, and you don’t want to mutate it but instead return a new array (because perhaps you want your React components to update), use a slice.

function removeFirst(src, element) {
  const index = src.indexOf(element)
  if (index === -1) return src
  return [...src.slice(0, index), ...src.slice(index + 1)]
}

This will give a new array every time.

const src = ["a","a","a","b","b","c"];
removeFirst(src, "a") // "a,a,b,b,c"
removeFirst(src, "b") // "a,a,a,b,c"
removeFirst(src, "c") // "a,a,a,b,b"

This might seem wasteful, but now you can depend on the identity of the response to change if the array itself changed. If they’re the same, and you pass this in as a property to a React component, the component knows it doesn’t have to change.

const src = ["a","a","a","b","b","c"];
removeFirst(src, "a") === src // false
removeFirst(src, "b") === src // false
removeFirst(src, "c") === src // false
removeFirst(src, "x") === src // true

Post a Comment

Your email is kept private. Required fields are marked *