Search code examples
javascriptarraysarray-difference

How to get the difference between two arrays in JavaScript?


Is there a way to return the difference between two arrays in JavaScript?

For example:

var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];

// need ["c", "d"]

Solution

  • This answer was written in 2009, so it is a bit outdated, also it's rather educational for understanding the problem. Best solution I'd use today would be

    let difference = arr1.filter(x => !arr2.includes(x));
    

    (credits to other author here)

    I assume you are comparing a normal array. If not, you need to change the for loop to a for .. in loop.

    function arr_diff (a1, a2) {
    
        var a = [], diff = [];
    
        for (var i = 0; i < a1.length; i++) {
            a[a1[i]] = true;
        }
    
        for (var i = 0; i < a2.length; i++) {
            if (a[a2[i]]) {
                delete a[a2[i]];
            } else {
                a[a2[i]] = true;
            }
        }
    
        for (var k in a) {
            diff.push(k);
        }
    
        return diff;
    }
    
    console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd']));
    console.log(arr_diff("abcd", "abcde"));
    console.log(arr_diff("zxc", "zxc"));