# 数组去重
数组去重的各种方法的整理👾
# 普通数组去重
// 需要去重的数组例子
const ary = [1, 2, 3, 4, 'a', 'b', 'c', 3, 4, 5, 1, 'b', 'd', 'a']
# new Set方法
function uniqueNewSet(ary) {
return [...new Set(ary)]
}
uniqueNewSet(ary) // [1, 2, 3, 4, "a", "b", "c", 5, "d"]
# filter方法
function uniqueFilter(ary) {
return ary.filter((item, index) => ary.indexOf(item) === index)
}
uniqueFilter(ary) // [1, 2, 3, 4, "a", "b", "c", 5, "d"]
# reduce方法
function uniqueReduce(ary) {
return ary.reduce((pre, cur) => {
!pre.includes(cur) && pre.push(cur)
return pre
}, [])
}
console.log(
uniqueReduce(ary) // [1, 2, 3, 4, "a", "b", "c", 5, "d"]
)
# 对象数组去重
// 需要去重的对象数组
const ary2 = [
{ id: '01', name: '一' },
{ id: '02', name: '二' },
{ id: '03', name: '三' },
{ id: '01', name: '一' },
{ id: '02', name: '二' },
{ id: '01', name: '一' },
{ id: '03', name: '三' }
]
# reduce方法1
function uniqueObj(ary, key) {
return ary.reduce((pre, cur) => {
!pre.find((item) => item[key] === cur[key]) && pre.push(cur)
return pre
}, [])
}
uniqueObj(ary2, 'id') // [{id: "01", name: "一"}, {id: "02", name: "二"}, {id: "03", name: "三"}]
# reduce方法2
function uniqueObj2(ary, key) {
const subObj = {}
return ary.reduce((pre, cur) => {
!subObj[cur[key]] && (subObj[cur[key]] = true) && pre.push(cur)
return pre
}, [])
}
uniqueObj2(ary2, 'id') // [1, 2, 3, 4, "a", "b", "c", 5, "d"]