Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude array from array in jQuery

Tags:

jquery

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]
like image 512
Wassim Gr Avatar asked Nov 22 '25 16:11

Wassim Gr


2 Answers

jQuery .not() method

You 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

jsFiddle demo

Complete

var exclude = [1,2,3,4];
var original = [0,1,2,3,4,5,6,7,8];
var finalArray = $(original).not(exclude).get();
like image 98
Richard Avatar answered Nov 25 '25 08:11

Richard


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.

like image 27
jackwanders Avatar answered Nov 25 '25 09:11

jackwanders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!