Logos DX
    Preparing search index...

    Function chunk

    • Splits an array into smaller arrays of the specified size.

      Divides a large array into multiple smaller arrays (chunks) of the given size. The last chunk may be smaller if the array length is not evenly divisible.

      Type Parameters

      • T

      Parameters

      • array: T[]

        array to split into chunks

      • size: number

        maximum size of each chunk

      Returns T[][]

      array of arrays, each containing up to size elements

      chunk([1, 2, 3, 4, 5, 6, 7], 3) // [[1, 2, 3], [4, 5, 6], [7]]
      chunk(['a', 'b', 'c', 'd'], 2) // [['a', 'b'], ['c', 'd']]
      chunk([1, 2], 5) // [[1, 2]]
      chunk([], 3) // []
      // Process large datasets in batches
      async function processBatches(items: any[], batchSize = 10) {
      const batches = chunk(items, batchSize);

      for (const batch of batches) {
      await Promise.all(batch.map(processItem));
      console.log(`Processed batch of ${batch.length} items`);
      }
      }
      // Paginate results
      function paginateResults<T>(results: T[], pageSize = 20) {
      const pages = chunk(results, pageSize);
      return pages.map((page, index) => ({
      page: index + 1,
      data: page,
      hasNext: index < pages.length - 1
      }));
      }