I have two arrays:
var a = ['a', 'as', 'sa'];
var b = ['sa', 'a', 'as'];
Is there anything special in shouldJS to test if these two arrays have same items? Anything Like
should(a).be.xyz(b)
that can test them? Here, xyz is what I am looking for.
To check if two arrays have the same elements:Use the every() to check if the arrays contain the same element at the same index. The every method only returns true if the condition is met for all array elements.
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.
Javascript arrays are objects and you can't simply use the equality operator == to understand if the content of those objects is the same. The equality operator will only test if two object are actually exactly the same instance (e.g. myObjVariable==myObjVariable , works for null and undefined too).
Because the effect of using Object. equals() to compare two arrays is often misconstrued as content equality, and because a better alternative exists in the use of reference equality operators, the use of the Object. equals() method to compare two arrays is disallowed.
A naive, but possibly sufficient solution would be to sort the arrays before comparing them:
should(a.sort()).be.eql(b.sort())
Note that sort()
works in-place, mutating the original arrays.
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