Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an idiomatic way to test array equality in Coffeescript?

Tags:

The expression

[1, 2, 3] == [1, 2, 3] 

evaluates to false in Coffeescript but is there a concise, idiomatic way to test array equality?

like image 902
Rob Fletcher Avatar asked Jun 21 '12 16:06

Rob Fletcher


People also ask

How do you check if two arrays are exactly equal?

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.

How do I check if an array is a match?

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.


1 Answers

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.

like image 137
epidemian Avatar answered Oct 20 '22 20:10

epidemian