sajad torkamani
function chunkArray<T>(array: Array<T>, chunkSize: number): Array<Array<T>> {
  if (chunkSize <= 0) {
    throw new Error("chunkSize must be greater than 0")
  }

  const chunkedArray: Array<Array<T>> = []
  
  for (let index = 0; index < array.length; index += chunkSize) {
    const chunk = array.slice(index, index + chunkSize);
    
    chunkedArray.push(chunk)
  }
  
  return chunkedArray
}

const NUMS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

console.log(chunkArray(NUMS, 2))
console.log(chunkArray(NUMS, 3))
console.log(chunkArray(NUMS, 5)

TypeScript playground

Tagged: JavaScript

Leave a comment

Your email address will not be published. Required fields are marked *