Skip to content

Instantly share code, notes, and snippets.

@topherPedersen
Created November 5, 2020 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save topherPedersen/6d08abfa54cf125f8046cf718ed90dd3 to your computer and use it in GitHub Desktop.
Save topherPedersen/6d08abfa54cf125f8046cf718ed90dd3 to your computer and use it in GitHub Desktop.
How to Strip Duplicate Items from 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 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);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment