Created
September 4, 2013 21:33
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.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); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var names = ["Jesse", "Pat", "John"]; | |
var extractedNames = _.extract(names, function(name) { | |
return name === "Jesse" || name === "Pat"; | |
}); | |
// names => ["John"] | |
// extractedNames => ["Jesse", "Pat"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow. And they do it much more beautifully! Thanks for the heads up.