Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  24] [ 3]  / answers: 1 / hits: 123626  / 12 Years ago, thu, june 7, 2012, 12:00:00

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?


More From » jquery

 Answers
17

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

[#85096] Tuesday, June 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rhett

Total Points: 671
Total Questions: 100
Total Answers: 102

Location: Hong Kong
Member since Tue, Oct 19, 2021
3 Years ago
rhett questions
Thu, Oct 28, 21, 00:00, 3 Years ago
Mon, Aug 2, 21, 00:00, 3 Years ago
Fri, Dec 11, 20, 00:00, 3 Years ago
Fri, Aug 7, 20, 00:00, 4 Years ago
Thu, Mar 26, 20, 00:00, 4 Years ago
;