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'
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");
const removeDuplicateWords = (s) => Object.keys(s.split(" ").reduce((fc, word) => ({ ...fc, [word]: true }), {})).join(" ");
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(" ");
}
const removeDuplicateWords = (s) => [...new Set(s.split(" "))].join(" ");