Chunking an Array in JavaScript: Four Ways Compared
Tags: javascript
Published: 2024-07-06 12:42:24

Chunking an array means splitting it into smaller arrays of a specified size. This is useful for data processing, pagination, and more. We’ll explore four methods to chunk an array and compare their performance.

First, let’s create an array of numbers from 1 to 10:

```javascript
const arr = Array.from({ length: 10 }, (_, i) => i + 1);
```
Array.from() is used to generate an array with elements from 1 to 10.
Now, we’ll look at four ways to chunk this array.

## Method 1: Using a For Loop

```javascript
function chunkArr(arr, size) {
 let res = [];
 for (let i = 0; i < arr.length; i += size) {
 res.push(arr.slice(i, size + i));
 }
 return res;
}

console.time("for");
console.log(chunkArr(arr, 2));
console.timeEnd("for");
```

**Output:**

```
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9, 10 ] ]
for: 4.363ms
```
**Explanation:** This function iterates through the array in steps of the specified chunk size. It slices the array at each step and adds the resulting sub-array to the result array (res). The performance measurement shows it took about 4.363 milliseconds.

## Method 2: Using `Array.reduce()`

```javascript
function chunkArr2(arr, size) {
 if (size <= 0) throw new Error('Chunk size must be a positive integer');
 return arr.reduce((acc, _, i) => {
 if (i % size === 0) acc.push(arr.slice(i, i + size));
 return acc;
 }, []);
}
console.time("reduce");
console.log(chunkArr2(arr, 2));
console.timeEnd("reduce");
```
**Output:**

```
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9, 10 ] ]
reduce: 0.069ms
```
**Explanation:** Here Array.reduce() is used to build the chunked array. It checks if the current index is a multiple of the chunk size and slices the array accordingly. This method is significantly faster, taking only about 0.069 milliseconds.

**Method 3: Using `Array.splice()`**

```javascript
let [list, chunkSize] = [arr, 2];
console.time('splice');
list = […Array(Math.ceil(list.length / chunkSize))].map(_ => list.splice(0, chunkSize));
console.timeEnd('splice');
console.log(list);
```
**Output:**
```
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9, 10 ] ]
splice: 0.048ms

```
**Explanation:** This approach uses Array.splice() in combination with Array.map() to chunk the array. It creates a new array with the required number of chunks and uses splice() to remove and collect chunks from the original array. This method is also very fast, taking about 0.048 milliseconds.

**Method 4: Recursive Approach**

```javascript
const chunk = function(array, size) {
 if (!array.length) {
 return [];
 }
 const head = array.slice(0, size);
 const tail = array.slice(size);
return [head, …chunk(tail, size)];
};

console.time(‘recursive’);
console.log(chunk(arr, 2));
console.timeEnd(‘recursive’);
```
**Output:**

```
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9, 10 ] ]
recursive: 4.372ms

```
**Explanation:** This recursive method splits the array into the first chunk (head) and the remaining elements (tail). It then recursively processes the tail, concatenating the results. While more elegant, this method is slower than the reduce and splice methods, taking about 4.372 milliseconds.

**Conclusion**
All four methods successfully chunk the array into sub-arrays of the specified size. However, their performance varies significantly:

1. For Loop: 4.363ms
2. Reduce: 0.069ms
3. Splice: 0.048ms
4. Recursive: 4.372ms

The splice and reduce methods are the fastest, making them preferable for performance-critical applications. While functional, the for loop and recursive methods are slower and might be less suitable for large datasets.

Depending on your needs and readability preferences, you can choose a suitable method for chunking arrays in your JavaScript projects.

You can find more approach [here](https://stackoverflow.com/questions/8495687/split-array-into-chunks?page=1&tab=scoredesc#tab-top)

**And Finally,**
Please don’t hesitate to point out any mistakes in my writing and any errors in my logic.

I’m appreciative that you read my piece.