2

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]
Wassim Gr
  • 568
  • 2
  • 8
  • 16

6 Answers6

6

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();
Richard
  • 8,110
  • 3
  • 36
  • 59
3
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.

jackwanders
  • 15,612
  • 3
  • 40
  • 40
  • 1
    `~` is a bitwise NOT operator which takes a value and flips each binary bit. we can use it in special cases like this because only `~(-1)` returns `0`, and `!0 == true`, so writing `!~(x)` is the same as `(x) === -1` – jackwanders Aug 16 '12 at 16:00
1
Array.prototype.difference = function(arr) {
    return this.filter(function(i) {return arr.indexOf(i) < 0; });
};
jeff
  • 8,300
  • 2
  • 31
  • 43
1

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] 
The Internet
  • 7,959
  • 10
  • 54
  • 89
0
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;
   })
}
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0

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();
Uchenna Nwanyanwu
  • 3,174
  • 3
  • 35
  • 59