DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Edited on

#25 - Remove consecutive duplicate words CodeWars Kata (7 kyu)

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(' ')
}
Enter fullscreen mode Exit fullscreen mode

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? 👇🤔

My Github
My twitter
Solve this Kata

Top comments (11)

Collapse
 
lexlohr profile image
Alex Lohr

This one you can solve with a single RegExp:

const removeConsecutiveDuplicates =
  (input) => input.replace(/(\w+) \1/g, "$1")
// \1 matches the last match made with (\w+)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
fjones profile image
FJones

Yeah, but backreferences are evil. ;)

Collapse
 
lexlohr profile image
Alex Lohr

Still pretty effective, especially in this case. ;)

Collapse
 
cesar__dlr profile image
Cesar Del rio

I don't know too much about regex, I think I need to do some research about it 😅
what does the "$1" do?

Collapse
 
lexlohr profile image
Alex Lohr

It inserts the first match inside brackets.

Thread Thread
 
cesar__dlr profile image
Cesar Del rio

Oh right, so it just leaves the first match and the other one gets replaced, am I rigth?

Thread Thread
 
lexlohr profile image
Alex Lohr

Exactly.

Thread Thread
 
cesar__dlr profile image
Cesar Del rio

cool 🔥

Collapse
 
matetlot profile image
Matetlot

What a conversation of genius, well donne guys !

Collapse
 
cesar__dlr profile image
Cesar Del rio

Thanks bro 🙌

Collapse
 
cesar__dlr profile image
Cesar Del rio

Great Solution, I didn't know that you could call the filtered array as a parameter! 🙌