如果追求性能,可以采用空间换时间的做法,在JS中最常见的处理方式就是构建Object,因为Object查找key的时间复杂度是O(1),而数组是O(n)
const list1 = [
{id: 0, name: ‘xiaomin’},
{id: 1, name: ‘xiaohong’},
];
const list2 = [
{id: 0, name: ‘xiaomin’},
{id: 1, name: ‘xiaohong’},
{id: 3, name: ‘xiaomin’},
{id: 4, name: ‘xiaohong’},
];
// 首先构造Object
const idSet = list1.reduce((acc, v) => {
acc[v.id] = true;
return acc;
}, {});
// 遍历list2,去掉在idSet中存在的id
const result = list2.filter(v => !idSet[v.id]);
console.log(result )
//一个对象剔除去重
const list3 = [
{id: 0, name: ‘xiaomin’},
{id: 1, name: ‘xiaohong’},
{id: 3, name: ‘xiaomin’},
{id: 4, name: ‘xiaohong’},
];
// 首先构造Object
//去重 请求数据 使用方法先将数据赋值一个变量在使用该方法
var obj = {};
let peon = list3.reduce(function (cur, next) {
obj[next.name] ? “” : obj[next.name] = true && cur.push(next);
return cur;
},[]) //设置cur默认类型为数组,并且初始值为空的数组
console.log(peon);