Skip to content

Instantly share code, notes, and snippets.

@jessegavin
Created September 4, 2013 21:33
Show Gist options
  • Save jessegavin/6443167 to your computer and use it in GitHub Desktop.
Save jessegavin/6443167 to your computer and use it in GitHub Desktop.
Here's a lodash mixin that works sort of like _.filter(), however the matching items will be removed from the source array.
_.mixin({
'multiSplice': function (array, indexes) {
if (!_.isArray(array) || !_.isArray(indexes) || !_.all(indexes, _.isNumber)) {
return [];
}
var results = [];
if (indexes.length > 0) {
var i = indexes.length - 1;
for (; i >= 0; i--) {
if (array.length > i) {
results.push(array.splice(indexes[i], 1)[0]);
}
}
}
return results.reverse();
},
'extract': function (collection, predicate) {
if (!_.isFunction(predicate)) {
return [];
}
var indexes = [];
_.each(collection, function (value, index) {
if (predicate.call(value, value, index, collection)) {
indexes.push(index);
}
});
return _.multiSplice(collection, indexes);
}
});
var names = ["Jesse", "Pat", "John"];
var extractedNames = _.extract(names, function(name) {
return name === "Jesse" || name === "Pat";
});
// names => ["John"]
// extractedNames => ["Jesse", "Pat"]
@jdalton
Copy link

jdalton commented Sep 5, 2013

Something like this is in Lo-Dash edge atm. It's called _.remove.

@jessegavin
Copy link
Author

Wow. And they do it much more beautifully! Thanks for the heads up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment