Recreating the lodash pull() method with vanilla JS
Just for fun, I started looking at methods in lodash and creating vanilla JS equivalents.
Today, we’re going to recreate the lodash _.pull()
method with vanilla JS.
What it does
The _.pull()
method takes an array, and removes any values that match what you pass in.
var array = ['a', 'b', 'c', 'a', 'b', 'c'];
_.pull(array, 'a', 'c');
// logs ['b', 'b']
console.log(array);
A vanilla JS pull()
method
For this one, we’ll use the Array.filter()
method.
First, let’s create a pull()
helper method. Unlike the lodash version, we’ll pass in an array for values
.
var pull = function (array, values) {
// Do stuff...
};
Next, we’ll call the Array.filter()
method on the array that’s passed in.
var pull = function (arr, values) {
return arr.filter(function (item) {
// Do stuff...
});
};
Finally, we’ll check if the current item is in the array of values
to remove using the Array.indexOf()
method.
If the method is greater than 0
, we’ll return a falsy value. Otherwise, we’ll return truthy.
var pull = function (arr, values) {
return arr.filter(function (item) {
return values.indexOf(item) < 0;
});
};
Unlike the lodash version, this returns a new immutable array, so we’ll need to assign it to a variable.
Now we can do this.
var array = ['a', 'b', 'c', 'a', 'b', 'c'];
var pulled = pull(array, ['a', 'c']);
// logs ['b', 'b']
console.log(pulled);