new Set去重的用法
2022-01-03 本文已影响0人
jesse28
使用Set数据结构去除重复对象:new Set(strings)进行转型。因为Set数据结构并非真正的数组,它类似于数组,并且成员值都是唯一的,没有重复,所以可以用来做去重操作。但是因为它是一个类似数组结构,所以需要转型为真正的数组去使用。所以需要用Array.from
new Set()里面需要接的是strings类型
const list1 =[" { name: '张三', age: 18, address: '北京' }"," { name: '张三', age: 18, address: '北京' }"]
console.log('去重',new Set(list1))//{" { name: '张三', age: 18, address: '北京' }"}
打印结果:
image.png
2.如果里面不是一个string类型,而是对象不会去重:
const list1 =[{ name: '张三', age: 18, address: '北京' },{ name: '张三', age: 18, address: '北京' }]
console.log('去重',new Set(list1))
打印结果如下:
image.png
案例:
const list =[
{ name: "张三", age: 18, address: "北京" },
{ name: "李四", age: 20, address: "天津" },
{ name: "张三", age: 18, address: "北京" },
]
其中张三和李四为重复对象;
使用Set数据结构去除重复对象
解析:因为数组里面是对象,所以我们这边先用map用JSON.stringify进行转化成string类型
const strings = list.map((item) => JSON.stringify(item))
console.log('strings', strings) //['{"name":"张三","age":18,"address":"北京"}', '{"name":"李四","age":20,"address":"天津"}', '{"name":"张三","age":18,"address":"北京"}']
然后就可以用new Set对这个数组进行去重,然后再用Array.from转化为真正的数组,
const removeDupList = Array.from(new Set(strings))
console.log('removeDupList',removeDupList)//['{"name":"张三","age":18,"address":"北京"}', '{"name":"李四","age":20,"address":"天津"}']
打印出来这就已经去重了:
image.png
然后再把数组里面的字符串类型转化为对象类型:
const removeDupList = Array.from(new Set(strings))
const result = removeDupList.map((item) => JSON.parse(item))
console.log('result',typeof result)
image.png