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

แบ่งอาร์เรย์เป็น Chunks แบบกระจาย (Round-Robin) - JavaScript

แบ่งอาร์เรย์เป็น n ชิ้นย่อย (Chunks) โดยกระจายเอลีเมนต์ทีละตัว (Round-Robin Distribution)

ตัวอย่าง

Input: [656, 756, 5345, 67, 43, 76, 54, 768, 34], n=3
Output: [[656, 67, 54], [756, 43, 768], [5345, 76, 34]]

Index:  0     1     2     3    4    5    6    7    8
Chunk:  0     1     2     0    1    2    0    1    2

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

const divideArray = (arr, size) => 
  arr.reduce((acc, val, i) => {
    const idx = i % size;
    if (!Array.isArray(acc[idx])) acc[idx] = [val];
    else acc[idx].push(val);
    return acc;
  }, []);

console.log(divideArray([656, 756, 5345, 67, 43, 76, 54, 768, 34], 3));

ผลลัพธ์

[ [656, 67, 54], [756, 43, 768], [5345, 76, 34] ]

วิธีอื่น: Chunk แบบต่อเนื่อง (Consecutive Chunks)

// [1,2,3,4,5,6], size=2 → [[1,2], [3,4], [5,6]]
const chunkConsecutive = (arr, size) => 
  Array.from({ length: Math.ceil(arr.length / size) }, (_, i) => 
    arr.slice(i * size, i * size + size)
  );

Round-Robin เหมาะสำหรับกระจายโหลด (Load Balancing) ส่วน Consecutive เหมาะสำหรับ Pagination