d
Amit DhamuSoftware Engineer
 

Chunking arrays

2 minute read 00000 views

Method 1

const chunk = (arr: unknown[], chunkSize: number) => {
  const result = []
  for (let i = 0; i < arr.length; i += chunkSize) {
    const c = arr.slice(i, i + chunkSize)
    result.push(c)
  }
  return result
}

Method 2

const chunk = (arr: unknown[], chunkSize: number) =>
  Array.from({ length: Math.ceil(arr.length / chunkSize) }, (_, i) =>
    arr.slice(i * chunkSize, (i + 1) * chunkSize)
  )

Usage

const chunks = chunk(
  [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }, { id: 7 }],
  2
)

console.log(chunks)

// Outputs
// [
//   [ { id: 1 }, { id: 2 } ],
//   [ { id: 3 }, { id: 4 } ],
//   [ { id: 5 }, { id: 6 } ],
//   [ { id: 7 } ]
// ]