Created
November 5, 2020 21:49
-
-
Save topherPedersen/6d08abfa54cf125f8046cf718ed90dd3 to your computer and use it in GitHub Desktop.
How to Strip Duplicate Items from 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 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