4 回答
TA贡献1785条经验 获得超8个赞
使用
Array.reduce
,您可以通过from
和to
变量对键对输入数组进行分组。对于重复,计数将增加,最后,结果将存储在
groupedBy
对象的每个键的值上。您只能使用 提取值
Object.values
。
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"},
];
const groupedBy = arr1.reduce((acc, cur) => {
const key = `${cur.from}_${cur.to}`;
acc[key] ? acc[key].count ++ : acc[key] = {
...cur,
count: 1
};
return acc;
}, {});
const result = Object.values(groupedBy);
console.log(result);
TA贡献1773条经验 获得超3个赞
您可以使用带有分隔符的组合键from和值。to
const
array = [{ from: "Monica", to: "Rachel" }, { from: "Monica", to: "Rachel" }, { from: "Monica", to: "Chandler" }, { from: "Monica", to: "Chandler" }, { from: "Ross", to: "Chandler" }, { from: "Ross", to: "Monica" }],
result = Object.values(array.reduce((r, { from, to }) => {
const key = [from, to].join('|');
r[key] ??= { from, to, count: 0 };
r[key].count++;
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献1803条经验 获得超3个赞
替代:
from
通过and组合对数组进行排序to
,在此之后,重复项将在排序后的数组中相邻。遍历排序的数组以删除重复项和计数。
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"},
];
var arr2 = arr1.sort((obj1, obj2) => (obj1.from + obj1.to).localeCompare(obj2.from + obj2.to));
for(var i = arr2.length - 1; i >= 0; i--){
if(i > 0 && arr2[i].from + arr2[i].to == arr2[i-1].from + arr2[i-1].to){
arr2[i-1].count = arr2[i].count ? arr2[i].count + 1 : 2;
arr2.splice(i, 1);
}else if(!arr2[i].count){
arr2[i].count = 1;
}
}
console.log(arr2);
TA贡献2051条经验 获得超10个赞
循环每个对象,获取它的值from并to进行比较。
const arr = [
{"from": "A", "to": "B"},
{"from": "A", "to": "C"},
{"from": "A", "to": "A"},
];
for (var i = 0; i < arr.length; i++) {
if (arr[i].from == arr[i].to) {
console.log('Matches!');
}
else {
console.log('No match');
}
}
添加回答
举报