Difference Between Lodash pull and pullAll
Lodash provides several utility methods to manipulate arrays, with
_.pull and _.pullAll being two of the most
commonly used for removing unwanted elements. Both functions mutate the
original array by stripping out specified values using strict equality
checks (SameValueZero). The primary difference between the
two lies entirely in how they accept the values to be removed:
_.pull accepts values as individual, comma-separated
arguments, while _.pullAll accepts values grouped within a
single array.
Understanding Lodash
_.pull
The _.pull method removes all provided values from an
array. It uses variadic arguments (rest parameters), meaning each
element you want to filter out must be passed as an individual
argument.
Syntax
_.pull(array, [values])Example
const _ = require('lodash');
let numbers = [1, 2, 3, 1, 2, 3];
// Values passed as individual arguments
_.pull(numbers, 2, 3);
console.log(numbers);
// Output: [1, 1]Notice that numbers is modified in place. Passing an
array of values directly into _.pull without spreading will
not work unless you are trying to remove a nested array that matches by
reference.
Understanding Lodash
_.pullAll
The _.pullAll method functions similarly to
_.pull, but instead of taking multiple individual
arguments, it accepts a single array containing all the values you wish
to remove.
Syntax
_.pullAll(array, values)Example
const _ = require('lodash');
let numbers = [1, 2, 3, 1, 2, 3];
// Values passed as a single array
_.pullAll(numbers, [2, 3]);
console.log(numbers);
// Output: [1, 1]Key Differences
| Feature | _.pull |
_.pullAll |
|---|---|---|
| Argument Type | Accepts separate arguments:
(array, val1, val2, ...) |
Accepts an array:
(array, [val1, val2, ...]) |
| Dynamic Inputs | Requires the spread operator
(...) if values are in an array |
Natively accepts an array of values |
| Mutation | Modifies the original array | Modifies the original array |
When to Use Which
- Use
_.pullwhen you know the exact, static values you want to exclude at design time and want a concise syntax (e.g.,_.pull(items, 'active', 'pending')). - Use
_.pullAllwhen the values to be removed are already stored in an array or generated dynamically at runtime (e.g.,_.pullAll(items, blacklistedIds)).
While you can achieve the same behavior using ES6 spread syntax with
_.pull (such as _.pull(items, ...blacklist)),
_.pullAll provides cleaner code and avoids argument-length
limits when handling large sets of data.