Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
168 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...