7

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?

3
  • 2
    Since you already know how to do it, what's the point in a lodash solution? Commented Feb 15, 2015 at 2:01
  • 1
    We already are using lodash extensively in the project. lodash has a bunch of helper functions for Arrays. So I figured there'd be a lodash function that would allow me to accomplish the same thing as without, but in one line of code. Commented Feb 15, 2015 at 2:31
  • 1
    Does it have to be an index or would the value work? lodash has several functions that takes the value rather than the index - without, difference, and it has pullAt which does what you want but returns the removed values, so it can't be chained. Commented Feb 15, 2015 at 4:42

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.