Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การแบ่งอาร์เรย์เป็น N อาร์เรียย่อยใน JavaScript

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่แบ่งอาร์เรย์ตัวเลขเป็น N กลุ่ม ซึ่งต้องเรียงจากกลุ่มใหญ่ไปกลุ่มเล็ก

ตัวอย่าง: ในโค้ดด้านล่าง แบ่งอาร์เรย์ 12 ตัวเลขเป็น 5 อาร์เรย์ ผลลัพธ์ควรแบ่งเท่าๆ กัน จากกลุ่มใหญ่ไปเล็ก:

const arr = [1,2,3,4,5,6,7,8,9,10,11,12];
const output = [[1,2,3] [4,5,6] [7,8] [9,10] [11,12]];

ฟังก์ชันควรรับอาร์เรย์เป็นอาร์กิวเมนต์แรก และจำนวน partition เป็นอาร์กิวเมนต์ที่สอง

ตัวอย่างโค้ด

const arr = [1,2,3,4,5,6,7,8,9,10,11,12];
const chunkArray = (arr = [], chunkCount) => {
  const chunks = [];
  while(arr.length) {
    const chunkSize = Math.ceil(arr.length / chunkCount--);
    const chunk = arr.slice(0, chunkSize);
    chunks.push(chunk);
    arr = arr.slice(chunkSize);
  };
  return chunks;
};
console.log(chunkArray(arr, 5));

ผลลัพธ์

ผลลัพธ์ที่แสดงในคอนโซลจะเป็นดังนี้:

[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ], [ 9, 10 ], [ 11, 12 ] ]