Skip to content

Instantly share code, notes, and snippets.

@kdubbels
Last active August 19, 2020 17:26
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 kdubbels/3399d2c829f85cd79cf5e693877e756e to your computer and use it in GitHub Desktop.
Save kdubbels/3399d2c829f85cd79cf5e693877e756e to your computer and use it in GitHub Desktop.
Remove duplicate words in a string
// 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