数据:
let arry = [ {name: "张三", age: 23, work: '计算机'}, {name: "王五", age: 29, work: '计算机'}, {name: "张兴", age: 30, work: '考古'}, {name: "刘豆豆", age: 23, work: '物理'}, {name: "李铁锤", age: 20, work: '英语'}, {name: "毛豆豆", age: 20, work: '英语'}, {name: "王五5", age: 23, work: '计算机'}, ]
第一种 :
利用filter+findIndex,通过判断数组中当前元素的下标与该元素第一次出现在数组中的下标是否一致来进行数组去重
function unRepeat(arry, key) { let newArr = arry.filter((currentValue, currentIndex, currentArr) => { return currentArr.findIndex(cV => cV[key] == currentValue[key]) == currentIndex }) return newArr }
第二种:
利用es6的new Map()的has属性进行筛选赋值
function unRepeat(arry, key) { const res = new Map(); return arry.filter((arr) => !res.has(arr[key]) && res.set(arr[key], 1)) }
第三种:
利用reduce()方法的累积器作用,在对由对象组成的数组进行遍历时,通过对象hasObj
来标记数组中每个元素id是否出现过。
function unRepeat(arry, key) { let hasObj = {}; return arry.reduce((cur, next) => { hasObj[next[key]] ? "" : (hasObj[next[key]] = true) && cur.push(next) return cur }, []) }
调用:
console.log(unRepeat(arry, 'work'))
结果: