เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ของค่าคงที่และตัวเลข n ฟังก์ชันควรคืนค่าอาร์เรย์ใหม่ที่แบ่งเป็น n ส่วนย่อย โดยที่ n จะน้อยกว่าหรือเท่ากับความยาวอาร์เรย์เสมอ
ตัวอย่าง: หากอาร์เรย์นำเข้าคือ:
const arr = [1,2,3,4,5,6,7,8,9,10]; const n = 3;
ผลลัพธ์ควรเป็น:
const output = [[1,2,3],[4,5,6],[7,8,9,10]];
ตัวอย่าง
โค้ดสำหรับนี้:
const arr = [1,2,3,4,5,6,7,8,9,10]; const n = 3; const divideIntoChunks = (arr, count) => { const res = []; const size = arr.length / count; let ind = 0; while (ind < arr.length) { res.push(arr.slice(ind, ind += size)); }; return res; }; console.log(divideIntoChunks(arr, n));ผลลัพธ์
ผลลัพธ์ในคอนโซล:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9, 10 ] ]