简单数组去重
<script lang="ts" setup>
const array = [1, 2, 1, 3, 3, 4, 1, 5];
const set = new Set(array);
const res1 = [...set];
console.info(res1);
const res2 = Array.from(set);
console.info(res2);
</script>
结果:
类声明
interface EntryBean {
id: number;
name: string;
}
示例:去掉对象数组中的重复元素
<script lang="ts" setup>
/**
* 对象数组去重
* @param arr
*/
const fun1 = (arr: EntryBean[]) => {
const res = new Map();
return arr.filter(arr => !res.has(arr.id) && res.set(arr.id, 1));
};
const data: EntryBean[] = [
{ id: 1, name: "1111" },
{ id: 2, name: "2222" },
{ id: 1, name: "1111" },
{ id: 4, name: "4444" },
{ id: 1, name: "1111" }
];
const res = fun1(data);
console.log(res);
</script>
结果:
示例:合并两个对象数组,并去除其中的重复元素
使用Map来进行数据的筛选和去重操作
<script lang="ts" setup>
/**
* 合并两个对象数组,相同元素只保留一份
* @param arr1
* @param arr2
*/
const fun2 = (arr1: EntryBean[], arr2: EntryBean[]): EntryBean[] => {
const map = new Map<number, EntryBean>();
for (const item of arr1) {
map.set(item.id, item);
}
for (const item of arr2) {
if (!map.has(item.id)) {
map.set(item.id, item);
}
}
return Array.from(map.values());
};
const data1: EntryBean[] = [
{ id: 1, name: "1111" },
{ id: 2, name: "2222" },
{ id: 3, name: "3333" }
];
const data2: EntryBean[] = [
{ id: 1, name: "1111" },
{ id: 2, name: "2222" },
{ id: 5, name: "5555" }
];
const res = fun2(data1, data2);
console.info(res);
</script>
结果: