Skip to content

Instantly share code, notes, and snippets.

@ZacharyL2
Last active March 23, 2023 06:49
Show Gist options
  • Save ZacharyL2/25cfae05fc88d8aeb4b08d16a880106d to your computer and use it in GitHub Desktop.
Save ZacharyL2/25cfae05fc88d8aeb4b08d16a880106d to your computer and use it in GitHub Desktop.
// πŸ‘ Solution 1
function unique(arr) {
const result = [];
for (const i of arr) {
let noRepeat = true;
for (const j of result) {
if (i === j) {
noRepeat = false;
break;
}
}
if (noRepeat) {
result.push(i);
}
}
return result;
}
// πŸ‘ Solution 2
function unique(arr) {
const result = [];
for (const item of arr) {
// πŸ‘‰ Option 1
if (!result.includes(item)) {
result.push(item);
}
// πŸ‘‰ Option 2
// if (result.indexOf(item) === -1) {
// result.push(item);
// }
}
return result;
}
function unique(arr) {
const result = arr.reduce((previousValue, currentValue) => {
// πŸ‘‰ Option 1
if (!previousValue.includes(currentValue)) {
previousValue.push(currentValue);
}
// πŸ‘‰ Option 2
// if (previousValue.indexOf(currentValue) === -1) {
// previousValue.push(currentValue);
// }
return previousValue;
}, []);
return result;
}
// πŸ‘ Solution 3
function unique(arr) {
const result = arr.filter((element, index) => arr.indexOf(element) === index);
return result;
}
// πŸ‘ Solution 4
function unique(arr) {
arr.sort((a, b) => a - b);
let result = [];
// πŸ‘‰ Option 1
for (let i = 0; i < arr.length; i += 1) {
if (arr[i] !== arr[i - 1]) {
result.push(arr[i]);
}
}
// πŸ‘‰ Option 2
// result = arr.reduce((previousValue, currentValue, currentIndex) => {
// if (arr[currentIndex] !== arr[currentIndex - 1]) {
// previousValue.push(currentValue);
// }
// return previousValue;
// }, []);
// πŸ‘‰ Option 3
// result = arr.filter((_, index) => arr[index] !== arr[index - 1]);
return result;
}
// πŸ‘ Solution 5
function unique(arr) {
const map = new Map();
let result = [];
// πŸ‘‰ Option 1
for (const item of arr) {
if (!map.has(item)) {
result.push(item);
map.set(item, true);
}
}
// πŸ‘‰ Option 2
// result = arr.reduce((previousValue, currentValue) => {
// if (!map.has(currentValue)) {
// previousValue.push(currentValue);
// map.set(currentValue, true);
// }
// return previousValue;
// }, []);
// πŸ‘‰ Option 3
// result = arr.filter((element) => {
// if (!map.has(element)) {
// map.set(element, true);
// return true;
// }
// return false;
// });
return result;
}
// πŸ‘ Solution 6
function unique(arr) {
// πŸ‘‰ Option 1
return [...new Set(arr)];
// πŸ‘‰ Option 2
// return Array.from(new Set(arr));
}
// πŸŽ‰
console.log(unique([1, 1, 3, 2, 2]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment