JavaScript: Comparing objects or arrays for equality (not reference)

Updated . Posted . Visible to the public. Repeats.

JavaScript has no built-in functions to compare two objects or arrays for equality of their contained values.

If your project uses Lodash Show archive.org snapshot or Underscore.js Show archive.org snapshot , you can use _.isEqual():

_.isEqual([1, 2], [2, 3]) // => false
_.isEqual([1, 2], [1, 2]) // => true

If your project already uses Unpoly Show archive.org snapshot you may also use up.util.isEqual() in the same way:

up.util.isEqual([1, 2], [2, 3]) // => false
up.util.isEqual([1, 2], [1, 2]) // => true

If you are writing server-side code in Node.js you can use isDeepStrictEqual():

import { isDeepStrictEqual } from 'util'
isDeepStrictEqual([1, 2], [2, 3]) // => false
isDeepStrictEqual([1, 2], [1, 2]) // => true

To compare two arrays for equality in a Jasmine spec assertion, see Jasmine: Testing complex types for equality.

Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2013-03-06 18:36)