Skip to content

Instantly share code, notes, and snippets.

@ca057
Last active February 4, 2018 22:13
Show Gist options
  • Save ca057/c88046441134d5d0443f0dd4b5e54365 to your computer and use it in GitHub Desktop.
Save ca057/c88046441134d5d0443f0dd4b5e54365 to your computer and use it in GitHub Desktop.
Find duplicates inside an array.
const duplicates = input => {
if (!Array.isArray(input)) return [];
const workingCopy = [...input];
const duplicatesSet = new Set();
// length of 1: no duplicate or already found
while (workingCopy.length > 1) {
const element = workingCopy.shift();
if (workingCopy.includes(element)) {
duplicatesSet.add(element);
}
}
return Array.from(duplicatesSet);
}
// example
console.log(duplicates(['a', 'b', 'a', 'c', 'c', 'c'])); // ['a', 'c']
const duplicates = (input, duplicatesSet = new Set()) => {
if (!Array.isArray(input)) return [];
const [element, ...rest] = input;
if (rest.includes(element)) {
duplicatesSet.add(element);
}
if (rest.length) return duplicates(rest, duplicatesSet);
return Array.from(duplicatesSet);
}
// example
console.log(duplicates(['a', 'b', 'a', 'c', 'c', 'c'])); // ['a', 'c']
const duplicates = input => {
if (!Array.isArray(input)) return [];
const sortedInput = [...input].sort();
const result = [];
let counter = 0;
while (counter < sortedInput.length - 1) {
const currentElement = sortedInput[counter];
let inc = 1;
if (currentElement === sortedInput[counter + inc]) {
result.push(sortedInput[counter]);
while(currentElement === sortedInput[counter + inc]) {
inc++;
}
}
counter = counter + inc;
}
return result;
}
// example
console.log(duplicates(['a', 'b', 'a', 'c', 'c', 'c'])); // ['a', 'c']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment