เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวอักษรและตัวเลขและแยกอาร์เรย์ (อาร์กิวเมนต์แรก) ออกเป็นกลุ่มตามความยาว n (อาร์กิวเมนต์ที่สอง) และส่งคืนอาร์เรย์สองมิติที่เกิดขึ้น
หากอาร์เรย์และตัวเลขเป็น −
const arr = ['a', 'b', 'c', 'd']; const n = 2;
จากนั้นผลลัพธ์ควรเป็น −
const output = [['a', 'b'], ['c', 'd']];
ตัวอย่าง
ให้เราเขียนโค้ด -
const arr = ['a', 'b', 'c', 'd'];
const n = 2;
const chunk = (arr, size) => {
const res = [];
for(let i = 0; i < arr.length; i++) {
if(i % size === 0){
// Push a new array containing the current value to the res array
res.push([arr[i]]);
}
else{
// Push the current value to the current array
res[res.length-1].push(arr[i]);
};
};
return res;
};
console.log(chunk(arr, n)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
[ [ 'a', 'b' ], [ 'c', 'd' ] ]