Wassim Gr
Wassim Gr

Reputation: 588

Exclude array from array in 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]

Upvotes: 2

Views: 5310

Answers (6)

Richard
Richard

Reputation: 8280

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();

Upvotes: 6

jackwanders
jackwanders

Reputation: 16050

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.

Upvotes: 3

The Internet
The Internet

Reputation: 8123

You don't need jQuery for this and its better for perf.

finalArray = [];
orig = [0,1,2,3,4,5,6,7,8];
exclude = [1,2,3,4];

orig.forEach(function(x) { if (exclude[x] === undefined) { finalArray.push(x) }}); 
//[0,5,6,7,8] 

Upvotes: 1

Uchenna Nwanyanwu
Uchenna Nwanyanwu

Reputation: 3204

Use jQuery's .not. You can find it here.

var original = [1,2,3];
var exclude = [1,2];

var tempArr = $(original).not(exclude);


var finalArray = tempArr .get();

Upvotes: 0

jeff
jeff

Reputation: 8348

Array.prototype.difference = function(arr) {
    return this.filter(function(i) {return arr.indexOf(i) < 0; });
};

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87083

function excludearrayfunction(original, exclude) {
  var temp = [];
  $.each(original, function(i, val) {
      if( $.inArray( val, exclude) != -1 ) {
        temp.push(val);
      }
  });
  return temp;
}

OR

function excludearrayfunction(original, exclude) {
   return $.grep(original, function(i, val) {
      return $.inArray(exclude, val) != -1;
   })
}

Upvotes: 0

Related Questions