断言已排序的对象数组

时间:2018-05-10 13:05:06

标签: javascript sorting chai assertions karma-mocha

我正在使用javascript测试框架(mocha,chai等)进行单元测试。如何使用其名称声明我的对象数组?

我可以使用localeCompare成功对此进行排序,但我在测试中没有得到我想要的东西。它只返回1-1

这是我想要排序的样本。

var Stuffs = [
     { name: "PWE", address: "1234567890" },
     { name: "NSA", address: "1234567890" },
     { name: "AVE", address: "1234567890" },
     { name: "QRE", address: "1234567890" },
  ]

如何将此声明为["AVE", "NSA", "PWE", "QRE"]

4 个答案:

答案 0 :(得分:2)

要获得所需的数组,您可以使用:

Stuffs.map(({ name }) => name).sort();

答案 1 :(得分:0)

使用柴

assert.deepInclude(Stuffs, {name: "AVE"});
assert.deepInclude(Stuffs, {name: "NSA"});
assert.deepInclude(Stuffs, {name: "QRE"});
assert.deepInclude(Stuffs, {name: "PWE"});

编辑:我可能误解了它意味着,如何断言数组具有这些值。

答案 2 :(得分:0)

您还可以使用reduce()数组方法,然后使用sort()

<强>样本

&#13;
&#13;
var Stuffs = [{ name: "PWE", address: "1234567890" },
     { name: "NSA", address: "1234567890" },
     { name: "AVE", address: "1234567890" },
     { name: "QRE", address: "1234567890" }];
     
let sortedArr = Stuffs.reduce((r,{name})=>r.concat(name),[]).sort((a,b)=>a.localeCompare(b));

console.log(sortedArr);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

首先,您需要一个排序数组来比较它。需要克隆原始数组(浅用于此),因为sort将修改它所调用的数组。使用from生成克隆,然后我们可以按字母顺序对新数组进行排序以获得所需的顺序。

const sortedStuffs = Array.from(stuffs).sort(({name: a}, {name: b}) => a.localeCompare(b));

最后使用every,我们可以比较每个元素的名称,看它们是否匹配。一旦失败,返回的值将为false

stuffs.every(({name}, i) => name === sortedStuffs[i].name);

完整的工作示例:

const stuffs = [
 {name: "PWE", address: "1234567890"},
 {name: "NSA", address: "1234567890"},
 {name: "AVE", address: "1234567890"},
 {name: "QRE", address: "1234567890"}
];

const sortedStuffs = Array.from(stuffs).sort(({name: a}, {name: b}) => a.localeCompare(b));

const isSorted = stuffs.every(({name}, i) => name === sortedStuffs[i].name);

console.log(isSorted);