1、git地址
2、作用
剔除一个数组中重复的元素,并输出新数组
3、例子和源码解析
3.1 例子
const dedupe = require('dedupe')
let fromer = [1, 3, 5, 4, 3]
let newer = dedupe(fromer)
console.log(newer) // 输出:[ 1, 3, 5, 4 ]
let fromerObjArray = [{'name': 'Frank'}, {'name': 'Sun'}, {'name': 'Quan'}, {'name': 'Huang'}, {'name': 'Gold'}]
let newerObjArray = dedupe(fromerObjArray)
console.log(newerObjArray) // 输出:[ { name: 'Frank' }, { name: 'Sun' }, { name: 'Quan' }, { name: 'Huang' }, { name: 'Gold'}]
let formerComplexArray = [
{ 'age': '28', 'name': 'Frank' },
{ 'age': '20', 'name': 'Sun' },
{ 'age': '21', 'name': 'Quan' },
{ 'age': '20', 'name': 'Huang' },
{ 'age': '20', 'name': 'Gold' }
]
let newerComplexArray = dedupe(formerComplexArray)
console.log(newerComplexArray) // 输出:[ { age: '28', name: 'Frank' }, { age: '20', name: 'Sun' }, { age: '21', name: 'Quan' }, { age: '20', name: 'Huang' }, { age: '20', name: 'Gold' } ]
let formerArrayFun = [
{ a: 2, b: 1 },
{ a: 1, b: 2 },
{ a: 1, b: 3 },
{ a: 1, b: 4 }
]
let newerAFunArray = dedupe(formerArrayFun, value => value.a)
let newerBFunArray = dedupe(formerArrayFun, value => value.b)
console.log(newerAFunArray) // 输出:[ { a: 2, b: 1 }, { a: 1, b: 2 } ]
console.log(newerBFunArray) // 输出:[ { a: 2, b: 1 }, { a: 1, b: 2 }, { a: 1, b: 3 }, { a: 1, b: 4 } ]
复制代码
3.2 源码
function dedupe (client, hasher) {
hasher = hasher || JSON.stringify
const clone = []
const lookup = {}
for (let i = 0; i < client.length; i++) {
let elem = client[i]
let hashed = hasher(elem)
if (!lookup[hashed]) {
clone.push(elem)
lookup[hashed] = true
}
}
return clone
}
module.exports = dedupe
复制代码
3.3 源码解析
1)该模块暴露出去的也是两个参数。如果第二个参数不存在的话,就赋值JSON.stringify;
2)接着遍历目标对象,对每个元素实例化或者进行hasher操作;
3)然后用lookup记录是否遍历过该元素,如果遍历过,在lookup保存该元素为true,并将元素保存到clone中;
4)如果传入hasher,那么将每个元素进行hasher操作,并在lookup记录是否操作过该元素。