Skip to content

Instantly share code, notes, and snippets.

@zhongyangxun
Created January 22, 2021 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhongyangxun/c51a2c18630fe012c3e17833178c96f9 to your computer and use it in GitHub Desktop.
Save zhongyangxun/c51a2c18630fe012c3e17833178c96f9 to your computer and use it in GitHub Desktop.
花式数组去重
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