1

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);
Th1
  • 269
  • 2
  • 12
  • 2
    Why are you splitting on space? Also, when you get to `input += '_'`, `input` is an array, not a string. I'd advise against overwriting your function parameters – Phil Feb 04 '21 at 22:36
  • 2
    `+=` when the left hand side is an array converts to string. You probably didn't mean to do that. – T.J. Crowder Feb 04 '21 at 22:37
  • 2
    Does this answer your question? [How can I split a string into segments of n characters?](https://stackoverflow.com/questions/6259515/how-can-i-split-a-string-into-segments-of-n-characters) – Daniel Beck Feb 04 '21 at 22:37
  • 1
    (If this is a job interview question or a school exercise, though, stick to tweaking your original code instead.) – Daniel Beck Feb 04 '21 at 22:39
  • @Phil the output should be an array – Th1 Feb 04 '21 at 22:41

1 Answers1

2

Instead of creating an array, you can directly access characters of the string with bracket notation.

const splitPairs = (input) => {
  if(!input) return [];
  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);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80