Using jQuery to compare two arrays of Javascript objects

MegaMatt picture MegaMatt · Nov 20, 2009 · Viewed 126.2k times · Source

I have two arrays of JavaScript Objects that I'd like to compare to see if they are the same. The objects may not (and most likely will not) be in the same order in each array. Each array shouldn't have any more than 10 objects. I thought jQuery might have an elegant solution to this problem, but I wasn't able to find much online.

I know that a brute nested $.each(array, function(){}) solution could work, but is there any built in function that I'm not aware of?

Thanks.

Answer

suDocker picture suDocker · Oct 11, 2011

There is an easy way...

$(arr1).not(arr2).length === 0 && $(arr2).not(arr1).length === 0

If the above returns true, both the arrays are same even if the elements are in different order.

NOTE: This works only for jquery versions < 3.0.0 when using JSON objects