Instructions
Your task is to remove all consecutive duplicate words from a string, leaving only first words entries.
For example:
Input: "alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta"
Output: "alpha beta gamma delta alpha beta gamma delta"
My solution:
const removeConsecutiveDuplicates = s => {
return s.split(' ').filter((w,i)=> w !== s.split(' ')[i+1]).join(' ')
}
Explanation
First I splitted the array into every space so I can get an array with every word, after that I filtered that array and I eliminated every element that is equal to the one next to it, after that I just joined the filtered array into a string
What do you think about this solution? 👇🤔
Top comments (11)
This one you can solve with a single RegExp:
Yeah, but backreferences are evil. ;)
Still pretty effective, especially in this case. ;)
I don't know too much about regex, I think I need to do some research about it 😅
what does the "$1" do?
It inserts the first match inside brackets.
Oh right, so it just leaves the first match and the other one gets replaced, am I rigth?
Exactly.
cool 🔥
What a conversation of genius, well donne guys !
Thanks bro 🙌
Great Solution, I didn't know that you could call the filtered array as a parameter! 🙌