Task: a string is set, it is necessary to return an array consisting of pairs of characters, if the last pair does not have enough characters to add instead of it "_" Example: "abcde" => [ab, cd, e_]

 function solution(str){ var arrLetters=[]; var result = []; arrLetters = str.split(""); if (arrLetters.length % 2 != 0) arrLetters.push("_"); for (let s=0;s<arrLetters.length;s++) {result.splice( result.length,0,arrLetters[s]+arrLetters[s+1])}; for (let s=0;s<arrLetters.length;s++) {result.splice(s+1,s)}; return (result);//(1) смотреть ниже } console.log(solution("abcde"), "ab", "cd", "e_"); 

The code is working, but I would like to improve it. If possible with a detailed description of your decisions. I tried to find a method that can be written to the array immediately 2 characters without unnecessary manipulations string (1)

    2 answers 2

     function solution(str) { return str.split('') .map((c, i, ar) => c + (ar[i + 1] ? ar[i + 1] : '_')) // объединяем каждый символ со следующим .filter((c, i) => 1 - i % 2); // убираем четные пары } console.log(solution("abcde"), "ab", "cd", "e_"); 

       const solution = (str) => { return str.match(/..?/g).map(x => {return x.length % 2 === 0 ? x : x + '_'}); } console.log(solution('abcde'), 'ab', 'cd', 'e_');