Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to compare two arrays of Javascript objects

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.

like image 867
MegaMatt Avatar asked Nov 20 '09 20:11

MegaMatt


People also ask

Can we compare two arrays in JavaScript?

While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.


1 Answers

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

like image 148
suDocker Avatar answered Oct 16 '22 01:10

suDocker