DEV Community

Cesar Del rio
Cesar Del rio

Posted on

#41 - Split Strings Codewars Kata (6 kyu)

Instructions

Task
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').

Examples:

  • 'abc' => ['ab', 'c_']
  • 'abcdef' => ['ab', 'cd', 'ef']

My solution:

function solution(str){
   var arr = str.split('')
   var res = []

   for(let i = 0; i<arr.length; i+=2){
     if(arr[i+1]) res.push(arr[i]+arr[i+1])
     else res.push(arr[i]+'_')
   }

  return res
}
Enter fullscreen mode Exit fullscreen mode

Explanation

First I made an array of the string, and an array to save the result

   var arr = str.split('')
   var res = []
Enter fullscreen mode Exit fullscreen mode

After that I used a loop to iterate through the array, and in every iteration I'll add two to the value of "i", so it iterates every two elements.
Inside of this loop I'll check if there is another element next to the one being iterated if it has another one It'll push the current element and the next one to the result array, if not it'll push the current element plus an underscore.

   for(let i = 0; i<arr.length; i+=2){
     if(arr[i+1]) res.push(arr[i]+arr[i+1])
     else res.push(arr[i]+'_')
   }
Enter fullscreen mode Exit fullscreen mode

At the end I just return the result array

   return res
Enter fullscreen mode Exit fullscreen mode

What do you think about this solution? 👇🤔

My Github
My twitter
Solve this Kata

Top comments (2)

Collapse
 
khaife profile image
K_A

super clean and nicely explained Thanks!

Collapse
 
cesar__dlr profile image
Cesar Del rio

Thanks for your comment bro, hope you enjoy my other posts!! 🙌🏼