Howdy_McGee Howdy_McGee - 1 year ago 87
Javascript Question

Compare 2 arrays which returns difference

What's the fastest/best way to compare two arrays and return the difference? Much like

in PHP. Is there an easy function or am I going to have to create one via
? or a

Answer Source

Working demo

Good link (Jquery Documentation): {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!


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 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download