67

What's the fastest/best way to compare two arrays and return the difference? Much like array_diff in PHP. Is there an easy function or am I going to have to create one via each()? or a foreach loop?

3

10 Answers 10

147

I know this is an old question, but I thought I would share this little trick.

var diff = $(old_array).not(new_array).get();

diff now contains what was in old_array that is not in new_array

12
  • 2
    short and sweet.. just like i like it.. i used that with $.merge() to concatenate differences in specific a specific order...
    – kingkode
    Oct 9, 2013 at 17:17
  • 1
    will this work if the array contains objects? I'm trying to compare objects within two arrays
    – Batman
    Jan 19, 2014 at 6:53
  • 2
    Here is a scenario. This works fine for $(['h','h','h','h','h']).not($(["a", "a", "a"])) but for an array like $(['h','h','h','h','h']).not($(["a", "a", "a", "h"])) (NOTICE the last "h" in the array) it returns an empty array. The difference is not returned. Hence, it is faulty. Feb 6, 2014 at 7:18
  • 2
    @VishnuNarang I think you are misunderstanding a few things here. Firstly how array differencing works, and secondly not reading the actual question the OP asked. Lets deal with the first misunderstanding. Returning an empty array in your second example is EXACTLY the right result. It is returning what was in the first array, that is not in the second (i.e nothing). This is the "difference" between the first array and the second. Secondly, the OP asked for a jQuery Function like PHP's (array_diff). This is it! Your example run through PHP's array_diff() function produces an empty array as well Feb 6, 2014 at 10:50
  • @VishnuNarang I am pretty confident that PHP's array_diff() function is not faulty. Feb 6, 2014 at 10:51
71

Working demo http://jsfiddle.net/u9xES/

Good link (Jquery Documentation): http://docs.jquery.com/Main_Page {you can search or read APIs here}

Hope this will help you if you are looking to do it in JQuery.

The alert in the end prompts the array of uncommon element Array i.e. difference between 2 array.

Please lemme know if I missed anything, cheers!

Code

var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var difference = [];

jQuery.grep(array2, function(el) {
        if (jQuery.inArray(el, array1) == -1) difference.push(el);
});

alert(" the difference is " + difference);​ // Changed variable name 
8
  • 8
    This method is cool, but should consider the case if array2's length is less than array1 Oct 30, 2012 at 11:31
  • 15
    More elegant : simply difference = $.grep(a1,function(x) {return $.inArray(x, a2) < 0}) Feb 15, 2013 at 15:02
  • 2
    Great answer. However would like to point out that you're using .grep like .each; should be difference = $.grep(array2, function(el) { return $.inArray( el, array1 ) == -1; })
    – PeterKA
    Aug 27, 2014 at 18:59
  • 1
    Dude, you are love :) I was stuck for about 2 days and you lead me to the other end. Jan 22, 2016 at 13:41
  • 1
    Fiddle for @Jocelyndelalande's comment: jsfiddle.net/cqsLvxod Mar 6, 2020 at 10:15
9

use underscore as :

_.difference(array1,array2)
4
  • 1
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
    – AlSki
    Feb 27, 2014 at 14:22
  • 2
    @AlSki it gives the answer to the question asked! compares the two arrays and returns the diff.
    – anurag_29
    Feb 28, 2014 at 13:31
  • 1
    @anurag_29 The question was how to do it with jQuery, not underscore. Mar 31, 2015 at 20:46
  • 1
    @AlSki When the answer is being posted YEARS later, t's appropriate, I think, to post an answer that involves the use of a different library than the question asked about, because that is a possible answer to the question - not knowing one way or the other if the OP, or others visiting the question years later, are aware of the library. Jun 25, 2015 at 4:55
3
var arrayDiff = function (firstArr, secondArr) {
    var i, o = [], fLen = firstArr.length, sLen = secondArr.length, len;


    if (fLen > sLen) {
        len = sLen;
    } else if (fLen < sLen) {
        len = fLen;
    } else {
        len = sLen;
    }
    for (i=0; i < len; i++) {
        if (firstArr[i] !== secondArr[i]) {
            o.push({idx: i, elem1: firstArr[i], elem2: secondArr[i]});  //idx: array index
        }
    }

    if (fLen > sLen) {  // first > second
        for (i=sLen; i< fLen; i++) {
            o.push({idx: i, 0: firstArr[i], 1: undefined});
        }
    } else if (fLen < sLen) {
        for (i=fLen; i< sLen; i++) {
            o.push({idx: i, 0: undefined, 1: secondArr[i]});
        }
    }    

    return o;
};
3
/** SUBTRACT ARRAYS **/
function subtractarrays(array1, array2){
    var difference = [];
    for( var i = 0; i < array1.length; i++ ) {
        if( $.inArray( array1[i], array2 ) == -1 ) {
                    difference.push(array1[i]);
        }
    }

    return difference;
}   

You can then call the function anywhere in your code.

var I_like    = ["love", "sex", "food"];
var she_likes = ["love", "food"];

alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty"!

This works in all cases and avoids the problems in the methods above. Hope that helps!

0
3

The short version can be like this:

const diff = (a, b) => b.filter((i) => a.indexOf(i) === -1);

result:

diff(['a', 'b'], ['a', 'b', 'c', 'd']);

["c", "d"]
2

In this way you don't need to worry about if the first array is smaller than the second one.

var arr1 = [1, 2, 3, 4, 5, 6,10],
    arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function array_diff(array1, array2){
    var difference = $.grep(array1, function(el) { return $.inArray(el,array2) < 0});
    return difference.concat($.grep(array2, function(el) { return $.inArray(el,array1) < 0}));;
}

console.log(array_diff(arr1, arr2));
2

if you also want to compare the order of the answer you can extend the answer to something like this:

Array.prototype.compareTo = function (array2){
    var array1 = this;
    var difference = [];
    $.grep(array2, function(el) {
        if ($.inArray(el, array1) == -1) difference.push(el);
    });
    if( difference.length === 0 ){
        var $i = 0;
        while($i < array1.length){
            if(array1[$i] !== array2[$i]){
                return false;
            }
            $i++;
        }
        return true;
    }
    return false;
}
1

Array operations like this is not jQuery's strongest point. You should consider a library such as Underscorejs, specifically the difference function.

0
1

This should work with unsorted arrays, double values and different orders and length, while giving you the filtered values form array1, array2, or both.

function arrayDiff(arr1, arr2) {
    var diff = {};

    diff.arr1 = arr1.filter(function(value) {
        if (arr2.indexOf(value) === -1) {
            return value;
        }
    });

    diff.arr2 = arr2.filter(function(value) {
        if (arr1.indexOf(value) === -1) {
            return value;
        }
    });

    diff.concat = diff.arr1.concat(diff.arr2);

    return diff;
};

var firstArray = [1,2,3,4];
var secondArray = [4,6,1,4];

console.log( arrayDiff(firstArray, secondArray) );
console.log( arrayDiff(firstArray, secondArray).arr1 );
// => [ 2, 3 ]
console.log( arrayDiff(firstArray, secondArray).concat );
// => [ 2, 3, 6 ]

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.