The expression
[1, 2, 3] == [1, 2, 3]
evaluates to false
in Coffeescript but is there a concise, idiomatic way to test array equality?
The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.
To conclude, to compare arrays to check for equality, Lodash's isEqual() function is the way to go if you need all the bells and whistles of checking that objects have the same class. The JSON. stringify() approach works well for POJOs, just make sure you take into account null.
If you are dealing with arrays of numbers, and you know that there are no nulls or undefined values in your arrays, you can compare them as strings:
a = [1, 2, 3] b = [1, 2, 3] console.log "#{a}" is "#{b}" # true console.log '' + a is '' + b # true
Notice, however, that this will break as soon as you start comparing arrays of other things that are not numbers:
a = [1, 2, 3] b = ['1,2', 3] console.log "#{a}" is "#{b}" # true
If you want a more robust solution, you can use Array#every
:
arrayEqual = (a, b) -> a.length is b.length and a.every (elem, i) -> elem is b[i] console.log arrayEqual [1, 2, 3], [1, 2, 3] # true console.log arrayEqual [1, 2, 3], [1, 2, '3'] # false console.log arrayEqual [1, 2, 3], ['1,2', 3] # false
Notice that it's first comparing the lengths of the arrays so that arrayEqual [1], [1, 2, 3]
doesn't return true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With