How to split an array into chunks

How to split an array into chunks

Using JavaScript and TypeScript

Sometimes, it proves advantageous to divide an array into smaller chunks, enhancing the efficiency of data processing or presentation. Luckily, both JavaScript and TypeScript offer practical approaches to achieve this.

In JavaScript, a straightforward method involves leveraging the slice() method. This function produces a copy of a designated section within the array, allowing for precise specification of start and end indices.

Consider the following example in JavaScript:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkSize = 3;
const chunks = [];

for (let i = 0; i < arr.length; i += chunkSize) {
  chunks.push(arr.slice(i, i + chunkSize));
}

console.log(chunks); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

In this instance, the original array undergoes segmentation into chunks of size 3 through a for loop and the slice() method. The resulting chunks are stored in a new array named chunks.

For TypeScript, a parallel strategy involves the use of a generic type known as Partial. This type enables the creation of an object with all optional properties, essentially allowing the formation of a partial array instead of a complete one.

Here's an example utilizing TypeScript:

const arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkSize = 3;
const chunks: Partial<number[]>[] = [];

for (let i = 0; i < arr.length; i += chunkSize) {
  chunks.push(arr.slice(i, i + chunkSize));
}

console.log(chunks); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

In this TypeScript example, we employ the generic type Partial<number[]>[] to craft a partial array that accommodates elements of type number[]. The loop structure and the slice() method mirror the JavaScript illustration.

In essence, the ability to partition an array into manageable chunks proves invaluable across diverse scenarios. While JavaScript relies on the slice() method, TypeScript introduces the concept of a partial array through the versatile Partial type. These techniques empower users to efficiently break down arrays into smaller units for streamlined processing.