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.
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With