Array removal

How to efficiently remove elements from an array in 2023.


function pull(arr, removeList) {
  var removeSet = new Set(removeList);
  return arr.filter(function (el) {
    return !removeSet.has(el);
  });
}
js

Context

As a seasoned JavaScript developer, there are situations where you need to remove specific elements from an array based on a list. Let's say, in an ecommerce site there is a list of items that a user wants to remove from their shopping cart or in case of a to-do list, items that the user wants to mark as completed. Well we can do both rather easily, let's find out how:

Usage

The pull() function provided in the above code is designed to remove specific elements from an array in a highly efficient manner. It takes two arguments: arr, which is the original array, and removeList, which is an array of elements to be removed from arr.

To speed up the process of removing elements from arr, the pull() function creates a Set called removeSet that stores the elements to be removed. The Set object is used instead of an array to improve the efficiency thanks to the built-in has() method which as a constant time complexity not matter how big the Set gets. Otherwise, we would have to use find() thus another loop, thus a loop inside a loop...

Finally, the filter() method is then used to create a new array that includes only the elements that are not present in removeSet.

// Primitives
pull([1, 2, 3, 3, 3], [1]); // [2, 3, 3, 3]
pull([1, 2, 3, 3, 3], [1, 3]); // [2]
js

Note: To follow up on the example we could extend this function to handle objects aswell in order to remove our unwanted elements from the user's shopping card simply like this:

function pull(arr, removeList) {
  var removeSet = new Set(removeList.map((obj) => obj.id));
  return arr.filter(function (el) {
    return !removeSet.has(el.id);
  });
}

const shoppingCard = [
  { id: 1, name: "Nike Air Max 1 OG" },
  { id: 2, name: "Air Jordan 1 Mid" },
];

const removeList = [{ id: 2, name: "Air Jordan 1 Mid" }];
pull(shoppingCard, removeList);
// [
//  { id: 1, name: "Nike Air Max 1 OG" },
// ]

// Sorry for the Air Jordan fans though 😎
js

Here, we simply iniliaze our set with the values we want to look for, in our case the product ids (but we could provide the key as variable when necessary), sorry for the Air Jordan fans though.

Last updated: February 5, 2023

âš¡ Who am i to talk about this? âš¡

Honestly i am no one, i've just been coding for 3 years now and i like to document every solutions to every problem i encounter. Extracting as much code snippets and tutorials i can so that if i ever need it again i just have to pop back here and get a quick refresher.

Feel free to me through this learning journey by providing any feedback and if you wanna support me: