# JS Algorithm – Chunk array

Palacio de Bellas Artes, México by https://unsplash.com/@azahed

Given an array and chunk size, divide the array into many subarrays where each subarray is of length size.

Examples
chunk([1, 2, 3, 4], 2) –> [[ 1, 2], [3, 4]]
chunk([1, 2, 3, 4, 5], 2) –> [[ 1, 2], [3, 4], [5]]
chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) –> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
chunk([1, 2, 3, 4, 5], 4) –> [[ 1, 2, 3, 4], [5]]
chunk([1, 2, 3, 4, 5], 10) –> [[ 1, 2, 3, 4, 5]]

### First solution:

function chunk(array, size) {
// Declaring new empty array to save the result
// this chunked array wrap the chunked arrays.
const chunked = [];

// To define from where index to which index the
// main array will be sliced
let index = 0;

// Go through every item in the main array
// 0 to the total of items in the array
while (index < array.length) {
// saving the sliced items into the chunked array
chunked.push(array.slice(index, index + size));

// Incrementing the index with the size (original)
index += size;
}

return chunked;
}

chunk([1, 2, 3, 4, 5], 2);

Result:

### Second solution:

function chunk(array, size) {
let chunked = [];

for (let item of array) {

let lastElement = chunked[chunked.length - 1];

if (!lastElement || lastElement.length === size) {
chunked.push([item]);
} else {
lastElement.push(item);
}
}

return chunked;
}

chunk([1, 2, 3, 4, 5], 2);

Result:

### Third solution:

function chunk(array, size) {
var results = [];

while (array.length) {
results.push(array.splice(0, size));
}
return results;
};

chunk([1, 2, 3, 4, 5], 2);

Result:

By Cristina Rojas.