Skip to content# Chunk method in JavaScript code challenge

### Problem

### Arguments

### Returns

### Example

### Solution (my initial approach)

### Solution (using slice)

### Appendix

## Newsletter

— 2 min read

Implement a function `chunk(array, [size=1])`

that splits the input array into groups of length `size`

and returns them within a **new** array. If array can't be split evenly, the final chunk will be the remaining elements. The function should not modify the original input array.

Initially, I encountered this code challenge while preparing for front-end interviews on GreatFrontEnd.

`array (Array)`

: The array to process.`[size=1] (number)`

: The length of each chunk.

*(Array)*: Returns the new array of chunks.

`1chunk(['a', 'b', 'c', 'd']); // => [['a'], ['b'], ['c'], ['d']]2chunk([1, 2, 3, 4], 2); // => [[1, 2], [3, 4]]3chunk([1, 2, 3, 4], 3); // => [[1, 2, 3], [4]]`

The function should return an empty array if the `array`

argument is empty.

Initially, while implementing it, I haven't found a good pattern to follow. I ended up with a solution that was not very elegant, and I was not happy with it. So I decided to look for other solutions online, and I found a very elegant solution on StackOverflow, what a surprise, right? So I decided to implement it myself to understand it better and it can be found in the code below.

We first checks if the input array is empty (has a length of 0). If it is, the function immediately returns an empty array `[]`

.

Next, we check if the length of the input array is `1`

or smaller than the specified chunk size. If either of these conditions is true, it means the array cannot be chunked further, so the function returns an array containing the input array itself as the only element. For example, if the array is `[1, 2, 3]`

, and the chunk size is `5`

, the function would return `[[1, 2, 3]]`

.

The function initialises two empty arrays: `chunked`

and `current`

.

We then iterate through each element of the input array using `array.forEach((elem, index) => {...})`

.

For each element in the input array, the code checks if the `current`

array has reached the desired chunk size (`size`

). If not, the element is added to the `current`

array using `current.push(elem)`

.

Once the `current`

array has reached the specified chunk size, it means a chunk is complete, so the `current`

array is added to the `chunked`

array using `chunked.push(current)`

. Then, the `current`

array is reset to an empty array to start forming the next chunk.

After the loop finishes iterating through the input array, there might be a partially filled `current`

array left if the input array length is not divisible by the chunk size. In that case, this remaining chunk is added to the `chunked`

array.

Finally, the function returns the `chunked`

array, which contains the input array split into smaller sub-arrays of the specified size.

```
1export default function chunk(array, size = 1) {2 if (!array.length) return [];3 if (array.length === 1 || array.length < size) return [array];4
5 let chunked = [];6 let current = [];7
8 array.forEach((elem, index) => {9 if (current.length < size) {10 current.push(elem);11 }12
13 if (current.length === size) {14 chunked.push(current);15 current = [];16 }17
18 if (array.length - 1 === index && current.length) {19 chunked.push(current);20 }21 });22
23 return chunked;24}
```

This solution, utilises a `for`

loop to achieve the same result. It employs the `slice()`

method to extract chunks from the input array and directly pushes them into the `chunked`

array. This approach avoids the need for maintaining a temporary array and the associated conditional checks. The second implementation is more concise and efficient for chunking the array.

```
1export default function chunk(array, size = 1) {2 const length = array == null ? 0 : array.length;3
4 if (!length || size < 1) {5 return [];6 }7
8 const chunked = [];9
10 for (let i = 0; i < array.length; i += size) {11 const chunk = array.slice(i, i + size);12 chunked.push(chunk);13 }14
15 return chunked;16}
```

Sign up to get updates when I write something new. No spam ever.

Subscribe to my Newsletter