Created
January 22, 2021 09:39
-
-
Save zhongyangxun/c51a2c18630fe012c3e17833178c96f9 to your computer and use it in GitHub Desktop.
花式数组去重
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function uniqueWithSet(arr) { | |
return Array.from(new Set(arr)); | |
} | |
function uniqueWithMap(arr) { | |
const map = {}; | |
const res = []; | |
for (item of arr) { | |
// 主要为了区分数字与字符串,例如数字 1 和字符串 '1' | |
const typeSign = typeof item; | |
const key = `${typeSign}-${item}`; | |
if (!map[key]) { | |
map[key] = 1; | |
res.push(item); | |
} | |
} | |
return res; | |
} | |
function uniqueWithReduce(arr) { | |
if (!arr || arr.length === 0) { | |
return []; | |
} | |
return arr.reduce((acc, cur) => { | |
if (acc.indexOf(cur) === -1) { | |
return [...acc, cur]; | |
} | |
return acc; | |
}, []); | |
} | |
function uniqueWithReduce2(arr) { | |
if (!arr || arr.length === 0) { | |
return []; | |
} | |
return arr.sort().reduce((acc, cur) => { | |
if (acc.length === 0 || acc[acc.length - 1] !== cur) { | |
acc.push(cur); | |
} | |
return acc; | |
}, []); | |
} | |
function uniqueWithFilter(arr) { | |
if (!arr || arr.length === 0) { | |
return []; | |
} | |
return arr.filter((item, index) => ( | |
arr.indexOf(item) === index | |
)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment