Skip to content

Instantly share code, notes, and snippets.

@Insidiae
Last active August 13, 2021 06:13
Show Gist options
  • Save Insidiae/d5e90d5e208bde2347a3aa2f1bb21c30 to your computer and use it in GitHub Desktop.
Save Insidiae/d5e90d5e208bde2347a3aa2f1bb21c30 to your computer and use it in GitHub Desktop.

Remove Duplicate Words

Your task is to remove all duplicate words from a string, leaving only single (first) words entries.

Example:

Input:

'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'

Output:

'alpha beta gamma delta'


Solution

function removeDuplicateWords (s) {
  //  Split the words into an array
  const arr = s.split(" ");
  //  Create a frequency counter object
  const fc = {}
  //  Store each word in frequency counter
  for (let word of arr) {
      fc[word] = true;
  }
  //  Return keys of frequency counter
  return Object.keys(fc).join(" ");
}

removeDuplicateWords("alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta");

🔥 Hotshot One-liner

const removeDuplicateWords = (s) => Object.keys(s.split(" ").reduce((fc, word) => ({ ...fc, [word]: true }), {})).join(" ");

Another solution using Sets

function removeDuplicateWords (s) {
  //  Split the words into an array
  const arr = s.split(" ");
  //  Create a Set from the array to remove duplicates
  const set = new Set(arr);
  //  Turn the set back into a string with spaces, then return
  return [...set].join(" ");
 }

🔥Hotshot One-liner

const removeDuplicateWords = (s) => [...new Set(s.split(" "))].join(" ");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment