Created
November 5, 2020 21:48
-
-
Save topherPedersen/8dac6a797bab6f8c476bb2c9a48f68b8 to your computer and use it in GitHub Desktop.
How to Find Duplicate Items in a JavaScript Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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