Right now I have this function:
function without(array, index) {
array.splice(index, 1);
return array;
}
I thought this would be something lodash would have a utility for, but looks like not.
Having this function allows me to do a one-liner that I can chain:
var guestList = without(guests, bannedGuest).concat(moreNames);
No way to achieve this without introducing a predicate function, using lodash?
_.without
already exists. Alternatively, you can use _.pull
as well, which mutates the given argument array.
var guests = ['Peter', 'Lua', 'Elly', 'Scruath of the 5th sector'];
var bannedGuest = 'Scruath of the 5th sector';
var bannedGuests = ['Peter', 'Scruath of the 5th sector'];
console.debug(_.without(guests, bannedGuest )); // ["Peter", "Lua", "Elly"]
Banning a collection of guests is not directly supported, but we can work around that easily:
// banning an array of guests is not yet supported, but we can use JS apply:
var guestList = _.without.apply(null, [guests].concat(bannedGuests));
console.debug(guestList); // ["Lua", "Elly"]
// or if you are feeling fancy or just want to learn a new titbit, we can use spread:
guestList = _.spread(_.without)([guests].concat(bannedGuests));
console.debug(guestList); // ["Lua", "Elly"]
jsFiddle
Alternatively, you can look at _.at
and _.pullAt
as well, which have similar behavior, except take array indexes instead of objects to remove.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With