Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.