1、利用Set的唯一特性,实现去重的目的(普通数组有效)
let a = [1, 2, 3, 4];
let b = [2, 4];
let c = new Set([...b, ...a]); // Set对象的特性,成员的值是唯一的,从而达到去重的目的
let s = Array.from(c); // Array.from() 把Set对象在转化为数组
console.log('d',d); // [ 2, 4, 1, 3 ]
2、对象数组的去重
// 假设id为每一个元素的唯一确定项,针对相同的id去重
let arr = [
{ id: 1, text: 1 },
{ id: 2, text: 2 },
{ id: 3, text: 3 },
{ id: 1, text: 1 },
];
let arrMap = new Map();
arr.forEach(item => {
arrMap.set(item.id, item);
})
let arrResult = [];
arrMap.forEach(item => {
arrResult.push(item);
});
console.log('arrMap',arrMap); // arrMap Map {1 => { id: 1, text: 1 },2 => { id: 2, text: 2 },3 => { id: 3, text: 3 }}
console.log('arrResult',arrResult); // [ { id: 1, text: 1 }, { id: 2, text: 2 }, { id: 3, text: 3 } ]