去重1
let arr=[{name:1,age:18},{name:2},{name:1,age:18}]
//结果===>[{name:1,age:18},{name:2}]
function unique(arr) {
return [...new Set(arr.map(e => JSON.stringify(e)))].map(e => JSON.parse(e))
}
function unique(arr) {
const map = new Map()
return arr.filter( item => !map.has(JSON.stringify(item)) && map.set(JSON.stringify(item), 1))
}
unique(arr)
去重2
let list = [
{ id: "1", content: "A"},
{ id: "2", content: "B"},
{ id: "3", content: "C"},
{ id: "4", content: "D"}
];
let arr = [
{id: "1",content: "C"},
{id: "2",content: "D"}
];
function listRemoveRepeat(x) {
let result = [];
for (let i = 0; i < x.length; i++) {
let flag = true;
let temp = x[i];
for (let j = 0; j < result.length; j++) {
// 普通数组 (temp === result[j])
if (temp.id === result[j].id) {
flag = false;
break;
}
}
if (flag) {
result.push(temp);
}
}
return result;
}
差集
function listDifference(x, y) {
let clone = x.slice(0);
for (let i = 0; i < y.length; i++) {
let temp = y[i];
for (let j = 0; j < clone.length; j++) {
// 普通数组 (temp === clone[j])
if (temp.id === clone[j].id) {
clone.splice(j, 1);
}
}
}
return listRemoveRepeat(clone);
}
并集
//调用去重2的方法listRemoveRepeat
function listConcat(x, y) {
return listRemoveRepeat(x.concat(y));
}
交集
//调用去重2的方法listRemoveRepeat
function listIntersection(x, y) {
let result = [];
for (let i = 0; i < y.length; i++) {
let temp = y[i];
for (let j = 0; j < x.length; j++) {
// 普通数组 (temp === clone[j])
if (temp.id === x[j].id) {
result.push(temp);
break;
}
}
}
return listRemoveRepeat(result);
}
(参考地址)https://www.cnblogs.com/wyuan-yuan/p/9430105.html