废话不多说,看代码!!!
let arr = [
{ userId: 1, name: '小红' },
{ userId: 3, name: '小黄' },
{ userId: 2, name: '小绿' },
{ userId: 1, name: '小蓝' },
{ userId: 2, name: '小紫' },
{ userId: 3, name: '小黑' }
];
// 双指针 + splice方法
function doubleForFilterArr(list, key) {
for (let i = 0; i < list.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (list[i][key] === list[j][key]) {
list.splice(j, 1)
j--
}
}
}
return arr
}
const newArr = doubleForFilterArr(arr, 'userId')
console.log(newArr)
// every 去重
function forEachFilterList(list, key) {
let temp = []
list.forEach(item => {
let check = temp.every(t => t[key] !== item[key])
check ? temp.push(item) : ''
})
return temp
}
console.log(forEachFilterList(arr, 'userId'))
//filter去重
function mapFilterList(list, key) {
let map = new Map()
for (let item of list) {
if (!map.has(item[key])) {
map.set(item[key], item)
}
}
return [...map.values()]
}
console.log(mapFilterList(arr, 'userId'))
// reduce 去重
function reduceFilterList(list, key) {
let object = {}
list = list.reduce((a, b) => {
object[b[key]] ? '' : object[b[key]] = a.push(b)
return a
}, [])
return list
}
console.log(reduceFilterList(arr, 'userId'))
// filter 去重
function filterList(list, key) {
let newList = []
newList = list.filter(item => !newList.includes(item[key]))
return newList
}
console.log(filterList(arr, 'userId'))
数组对象中去重的方式还有很多,可以在评论区讨论一下,谢谢观看,记得点赞 + 收藏!!!
版权声明:本文为weixin_46079570原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。