Expect Arrays to be equal ignoring order Ask Question

Expect Arrays to be equal ignoring order Ask Question

With Jasmine is there a way to test if 2 arrays contain the same elements, but are not necessarily in the same order? ie

array1 = [1,2,3];
array2 = [3,2,1];

expect(array1).toEqualIgnoreOrder(array2);//should be true

ベストアンサー1

Edit

Jasmine 2.8 adds arrayWithExactContents that will succeed if the actual value is an Array that contains all of the elements in the sample in any order.

See keksmasta's answer


Original (outdated) answer

If it's just integers or other primitive values, you can sort() them before comparing.

expect(array1.sort()).toEqual(array2.sort());

If its objects, combine it with the map() function to extract an identifier that will be compared

array1 = [{id:1}, {id:2}, {id:3}];
array2 = [{id:3}, {id:2}, {id:1}];

expect(array1.map(a => a.id).sort()).toEqual(array2.map(a => a.id).sort());

おすすめ記事