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]
1

6 Answers 6

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();
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

~ 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
1
Array.prototype.difference = function(arr) {
    return this.filter(function(i) {return arr.indexOf(i) < 0; });
};

1 Comment

modifying prototypes for native objects is generally not ideal.
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] 

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.