如果有遇到一个数组中存储多个对象,有部分对象的某一个键值是相同的,需要过滤掉重复项的实现方案
const arr =[
{
"count": 1095,
"month": "三月",
},
{
"count": 1106,
"month": "三月",
},
{
"count": 987,
"month": "四月",
},
{
"count": 1166,
"month": "四月",
},
{
"count": 753,
"month": "五月",
},
{
"count": 891,
"month": "五月",
}
];
const res = new Map();
const new2 = arr.filter(item => !res.has(item.month) && res.set(item.month, 1));
console.log(arr.length, new2);
数组合并去重
const a = [{ id: 1, name: 2 }];
const b = [{ id: 1, name: 3 }];
const c = [...a, ...b];
var arr1 = [
{ id: 1, name: 'car2' },
{ id: 2, name: 'car3' },
];
var arr2 = [
{ id: 1, name: 'acar22' },
{ id: 2, name: 'acar32' },
{ id: 3, name: 'acar3' },
];
const combined = (arr1, arr2, type) =>
arr2.reduce((acc, cur) => {
const target = acc.find(e => e[type] === cur[type]);
// console.log(target);
if (target) {
Object.assign(target, cur);
} else {
acc.push(cur);
}
return acc;
}, arr1);
console.log(c, '引用类型,所以去重失败');
console.log(combined(arr1, arr2, 'id'), '成功合并并去重');