I have this problem to solve:
split the input string into pairs of characters. If the input string has a length that is odd, then it should replace the missing second character of the final pair with an underscore
'_'
.
I solved it with this solution, and it works fine with odd string, but with even string, it gives me undefined
which is not correct. because it has to just split the characters into pairs.
The input is a string and the output should be an array
for example
splitPairs('abc');//--> [ 'ab', 'c_' ]
This is my code:
const splitPairs = (input) => {
if(!input) return [];
input = input.split(' ');
let pairs = [];
if(input.length % 2 !== 0) {input += '_'}
for(let i = 0; i < input.length; i+= 2) {
pairs.push(`${input[i] + input[i+1]}`)
}
return pairs;
}
let result1 = splitPairs('abc');//--> [ 'ab', 'c_' ]
console.log(result1);
let result2 = splitPairs('abcdef');//--> [ 'ab', 'cd', 'ef' ]
console.log(result2);
let result3 = splitPairs('retrograde');//--> [ 're', 'tr', 'og', 'ra', 'de' ]
console.log(result3);
let result4 = splitPairs('endurance');//--> [ 'en', 'du', 'ra', 'nc', 'e_' ]
console.log(result4);
let result5 = splitPairs('');//--> []
console.log(result5);