Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created November 5, 2020 21:48
Show Gist options
  • Save topherPedersen/8dac6a797bab6f8c476bb2c9a48f68b8 to your computer and use it in GitHub Desktop.
Save topherPedersen/8dac6a797bab6f8c476bb2c9a48f68b8 to your computer and use it in GitHub Desktop.
How to Find Duplicate Items in a JavaScript Array
// Duplicates: Bob, Aaron, Frank
const arrayWithDuplicates = ["Aaron", "Bob", "Chris", "Dave", "Edward", "Bob", "Aaron", "Frank", "George", "Frank", "Henry", "Bob", "Bob", "Aaron", "Aaron", "Frank"];
function findDuplicates(arrayWithDuplicates) {
let duplicates = [];
arrayWithDuplicates.forEach( (value, index) => {
const indexWhereValueFirstAppears = arrayWithDuplicates.findIndex( (value_) => {
return value_ === value;
});
const indexWhereValueLastAppears = arrayWithDuplicates.lastIndexOf(value);
if (index !== indexWhereValueFirstAppears && index === indexWhereValueLastAppears) {
duplicates.push(value);
}
});
return duplicates;
}
const duplicatesFound = findDuplicates(arrayWithDuplicates);
duplicatesFound.forEach( (duplicate) => {
console.log("Duplicate: " + duplicate);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment