Last active
August 19, 2020 17:26
-
-
Save kdubbels/3399d2c829f85cd79cf5e693877e756e to your computer and use it in GitHub Desktop.
Remove duplicate words in a string
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
// Remove duplicate words in a string | |
// Uses ES5 | |
function removeDuplicates(str) { | |
const split = str.split(' '); | |
const newArray = split.reduce((accumulator, currentValue) => { | |
if (!accumulator.includes(currentValue)) { | |
accumulator.push(currentValue); | |
} | |
return accumulator; | |
}, []); | |
return newArray.join(' '); | |
} | |
// one line using ES6 | |
const removeDuplicates2 = str => [... new Set("This is is a test test string".split(' '))].join(' '); | |
const testString = "This is is a test test string"; | |
removeDuplicates(testString); // "This is a test string" | |
removeDuplicates2(testString); // "This is a test string" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment