Issue #225, adding _.union, _.difference, to complement _.without and _.intersection.

This commit is contained in:
Jeremy Ashkenas
2011-07-12 16:48:30 -04:00
parent 942d63129b
commit 0ec859a142
2 changed files with 29 additions and 8 deletions

View File

@@ -327,8 +327,7 @@
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
var values = slice.call(arguments, 1);
return _.filter(array, function(value){ return !_.include(values, value); });
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
@@ -341,9 +340,15 @@
}, []);
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(_.flatten(arguments));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersect = function(array) {
// passed-in arrays. (Aliased as "intersect" for back-compat.)
_.intersection = _.intersect = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
@@ -352,6 +357,12 @@
});
};
// Take the difference between one array and another.
// Only the elements present in just the first array will remain.
_.difference = function(array, other) {
return _.filter(array, function(value){ return !_.include(other, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {