I want to simply exclude some array elements from another array and get the result using js and jQuery. I find my self doing a double .each() loop...
var exclude = new Array();
exclude = [1,2,3,4];
var original = new Array();
original = [0,1,2,3,4,5,6,7,8];
var finalarray = excludearrayfunction(original, exclude); // [0,5,6,7,8]
.not() methodYou can use the jQuery .not method to exclude items from a collection like so:
var exclude = [1,2,3,4];
var original = [0,1,2,3,4,5,6,7,8];
var result = $(original).not(exclude);
This will return us a jQuery object, to select the result as an array we can simply do:
var finalArray = result.get();
// result: 0,5,6,7,8
var exclude = [1,2,3,4];
var original = [0,1,2,3,4,5,6,7,8];
var finalArray = $(original).not(exclude).get();
var exclude = [1,2,3,4];
var original = [0,1,2,3,4,5,6,7,8];
var finalarray = $.grep(original,function(el,i) {
return !~$.inArray(el,exclude);
});
!~ is a shortcut for seeing if a value is equal to -1, and if $.inArray(el,exclude) returns -1, you know the value in the original array is not in the exclude array, so you keep it.
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