How to Find and Strip Duplicate Items from an Array in JavaScript (the Easy Way)

I found today at work I needed to identify duplicates in an array, and happened to stumble upon this highly ranked StackOverflow post full of hard to understand answers. Whenever I write code at work, I really want to make sure that I understand all of the code that I contribute to the company’s codebase and that I’m not blindly copying and pasting directly from StackOverflow. So if you’ve happened to find this blog post looking for something a little easier to understand than many of the other answers out there on the internet, maybe consider my solution:

// 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);
});

And if you need to simply strip duplicates from an array, try:

// Duplicates: Bob, Aaron, Frank
const arrayWithDuplicates = ["Aaron", "Bob", "Chris", "Dave", "Edward", "Bob", "Aaron", "Frank", "George", "Frank", "Henry", "Bob", "Bob", "Aaron", "Aaron", "Frank"];
function stripDuplicates(arrayWithDuplicates) {
let uniques = [];
arrayWithDuplicates.forEach( (value, index) => {
const indexWhereValueFirstAppears = arrayWithDuplicates.findIndex( (value_) => {
return value_ === value;
});
if (index === indexWhereValueFirstAppears) {
uniques.push(value);
}
});
return uniques;
}
const arrayWithNoDuplicates = stripDuplicates(arrayWithDuplicates);
arrayWithNoDuplicates.forEach( (unique) => {
console.log("Unique: " + unique);
});
 

topherPedersen