Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return array without element at index n in lodash

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?

like image 528
core Avatar asked Feb 15 '15 01:02

core


1 Answers

_.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.

like image 181
Benny Bottema Avatar answered Sep 26 '22 11:09

Benny Bottema