Compare two Arrays Javascript - Associative

user135998 picture user135998 · Jul 10, 2009 · Viewed 34.1k times · Source

I have searched on here for a quality method to compare associative arrays in javascript. The only decent solution I have found is the PHP.JS project which has some comparative array functions. The only problem is that these functions consider the first array as the key to the second. In my situation at least both arrays do not always have the same # of keys nor the same keys. This causes the functions to output results that do not include keys that may not have existed in array1 but existed in array2. The only thing I can think of so far is to run the array_diff_associative() function twice with the arguments flipped and then combine them(which seems problematic since the first argument again is used as the keys to the second).

Any suggestions? Thank you.

Answer

Brainware picture Brainware · Dec 11, 2014

This is an old question, but since it comes up first in a google search for comparing arrays, I thought I would throw in an alternative solution that works even when the array has two different objects with the same values.

function arrays_equal(a, b) {
    return JSON.stringify(a) == JSON.stringify(b);
}

Note: This is order dependent, so if order doesn't matter, you can always do a sort ahead of time.