เราจำเป็นต้องเขียนฟังก์ชัน 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' ]