문자열과 숫자 n을 받는 JavaScript 함수를 작성해야 하고(n이 문자열의 길이를 정확히 나누도록) 문자열의 동일한 부분 n을 포함하는 길이가 n인 문자열 배열을 반환해야 합니다.
예시
이에 대한 코드는 -
const str = 'we will be splitting this string into parts'; const num = 6; const divideEqual = (str, num) => { const len = str.length / num; const creds = str.split("").reduce((acc, val) => { let { res, currInd } = acc; if(!res[currInd] || res[currInd].length < len){ res[currInd] = (res[currInd] || "") + val; }else{ res[++currInd] = val; }; return { res, currInd }; }, { res: [], currInd: 0 }); return creds.res; }; console.log(divideEqual(str, num));
출력
콘솔의 출력 -
[ 'we will ', 'be split', 'ting thi', 's string', ' into pa', 'rts' ]