Reputation: 12072
Looking at the underscore array methods, I dont see what I want to accomplish.
This removes 0
and 1
from the array:
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]
What if I need only 0
and 1
?
=> [1, 1, 0 ,1]
Underscorde would make me write less javascript code.
Clarity:
Example if 0, 1
is in the array, leave all values of 1
's and 0
's.
Upvotes: 3
Views: 764
Reputation: 303
The simplest underscore
way I found is this:
var arr = [1, 2, 1, 0, 3, 1, 4];
console.log(_.difference(arr, _.without(arr, 1, 0)));
or if you have your args in an array:
console.log(_.difference(arr, _.difference(arr, [1, 0])));
Upvotes: 0
Reputation: 2241
Here is what I found:
var allArray = [1, 2, 1, 0, 3, 1, 4];
var leaveOnly = [1, 0];
var result = _.filter(allArray, _.partial(_.contains, leaveOnly)); // [1, 1, 0, 1]
_.filter
, _.contains
, _.partial
JSFiddle: https://jsfiddle.net/eeLcrmvt/
If you are going to use this quite often, you can create a mixin:
_.mixin({
filterOut: function(arr, leave) {
return _.filter(arr, _.partial(_.contains, leave))
}
});
var result = _.filterOut([ 1, 2, 0, 1, 4, 3, 1 ], [ 0, 1 ]);
console.log(result); // [ 1, 0, 1, 1 ]
Upvotes: 3
Reputation: 4656
The underscore
way
var zerosones = _.filter([1, 2, 1, 0, 3, 1, 4], function(num){
return (num === 0 || num === 1);
});
=> [1, 1, 0, 1]
using _.filter method
Without underscore
( es5
) you can use Array#filter with a pretty good compatibility
var completeArray = [1, 2, 1, 0, 3, 1, 4];
completeArray = completeArray.filter(function(value){
return (value === 1 || value === 0)
});
console.log(completeArray); //[1, 1, 0, 1]
Upvotes: 0