我有一系列对象,例如:
const arr1 = [
{"from":"Monica","to":"Rachel"},
{"from":"Monica","to":"Rachel"},
{"from":"Monica","to":"Chandler"},
{"from":"Monica","to":"Chandler"},
{"from":"Ross","to":"Chandler"},
{"from":"Ross","to":"Monica"},
];
我想对两个键(“from”和“to”)相同的所有唯一实例进行排序和计数。
我可以成功地计算每个案例,只比较一个键('from' 或 'to'),但我找不到关于如何比较两者的解决方案。
这是我的示例代码:
let arr2 = Object.values(arr1.reduce((c, { from, to }) => {
c[from] = c[from] || { from, to, count: 0 };
c[from].count++;
return c;
}, {}));
console.log(arr2);
这是我现在得到的结果(因为代码只比较“来自”键):
console.log(arr2);
// Array(2)
// 0: {from: "Monica", to: "Rachel", count: 4}
// 1: {from: "Ross", to: "Chandler", count: 2}
// length: 2
这是我想要达到的结果:
console.log(arr2);
// Array(2)
// 0: {from: "Monica", to: "Rachel", count: 2}
// 1: {from: "Monica", to: "Chandler", count: 2}
// 2: {from: "Ross", to: "Chandler", count: 1}
// 3: {from: "Ross", to: "Monica", count: 1}
// length: 4
慕的地10843
慕容3067478
繁星点点滴滴
侃侃无极
相关分类