Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should.js: check if two arrays contain same strings

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.

like image 916
Samman Bikram Thapa Avatar asked Jul 11 '16 20:07

Samman Bikram Thapa


People also ask

How do you check if 2 arrays have the same values JS?

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.

How do I check if two arrays have the same contents?

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.

Does == work for arrays in JavaScript?

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).

Why comparing arrays using == does not work?

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.


1 Answers

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.

like image 90
TimoStaudinger Avatar answered Oct 27 '22 15:10

TimoStaudinger