普通数组
let a = [1, 2, 3, 4, 5, 6]
let b = [4, 5, 6, 7, 8, 9]
let RemoveSame = new Set([...a, ...b])
console.log(new Set([...a, ...b]))
let SamePart = a.filter(item => b.includes(item))
console.log(SamePart)
let Difference = a.filter(item => !b.includes(item))
console.log(Difference)
let SamePartAll = Array.from(RemoveSame)
Difference = SamePartAll.filter(item => !SamePart.includes(item))
console.log(Difference)
es6数组去重
function newArr(arr){
return Array.from(new Set(arr))
}
var arr = [1,1,2,9,6,9,6,3,1,4,5];
console.log(newArr(arr))
对象数组
let arr1 = [
{ key: 1, id: 8, val: "a" },
{ key: 2, id: 9, val: "b" },
{ key: 4, id: 14, val: "c" },
{ key: 3, id: 15, val: "d" },
];
let arr2 = [
{ key: 1, id: 8, val: "a" },
{ key: 2, id: 9, val: "b" },
{ key: 5, id: 8, val: "e" },
{ key: 6, id: 9, val: "f" },
{ key: 5, id: 19, val: "g" },
{ key: 6, id: 22, val: "h" },
{ key: 5, id: 19, val: "g" },
{ key: 6, id: 22, val: "h" }
];
let arr = [...arr1, ...arr2]
let arr3;
arr3 = [...arr2].filter(x => [...arr1].every(y => y.id !== x.id));
console.log("根据关键字取差集=", arr3)
arr3 = arr2.filter(v => {
var str = JSON.stringify(v);
return arr1.every(v => JSON.stringify(v) != str);
});
console.log("全部匹配取差集=", arr3);
const hash = {};
const newArray = arr.reduce((item:any, next:any) => {
hash[next.id] ? '' : hash[next.id] = true && item.push(next);
return item;
}, [])
console.info('根据关键字去重后的数组=', newArray);
const keyArr: any = [];
arr.forEach((element: any, index: any) => {
keyArr.push(element.key);
});
const newArr: any = [];
const newKey = new Set(keyArr);
newKey.forEach(item => {
const index = keyArr.findIndex(item2 => item2 === item);
newArr.push(arr[index]);
})
console.info('根据关键字去重后的数组2:', newArr);
let res = new Map();
this.dialog.chooseList = await this.dialog.chooseList.filter(
(item: any) => !res.has(item.itemId) && res.set(item.itemId, 1)
);
arr3 = [...arr2].filter(x => [...arr1].some(y => y.id === x.id));
console.log("关键字交集=", arr3);