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]
// Objects
pull([
{ id: 1, name: "Nike Air Max 1 OG" },
{ id: 2, name: "Air Jordan 1 Mid" },
], [{ id: 2, name: "Air Jordan 1 Mid" }])
// [
// { id: 1, name: "Nike Air Max 1 OG" },
// ]
// Sorry for the Air Jordan fans though π
Note: To follow up on the example we could extend this function 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" },
// { id: 2, name: "Air Jordan 1 Mid" }
// ]
So we simple initialize our set with the values we want to look for, in our case the product ids, sorry for the Air Jordan fans though.
Conclusion
The pull function efficiently removes specific elements from an array using a Set. This approach ensures fast removal without nested loops, enhancing performance and simplicity in your code. Happy coding!
Top comments (0)