期望数组相等,忽略顺序 [英] Expect Arrays to be equal ignoring order

查看:13
本文介绍了期望数组相等,忽略顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Jasmine 是否可以测试 2 个数组是否包含相同的元素,但顺序不一定相同?即

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

推荐答案

如果只是整数或者其他原始值,可以sort() 比较之前的它们.

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

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

如果它的对象,将其与 map() 函数提取将要比较的标识符

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());

这篇关于期望数组相等,忽略顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆