# Splitting arrays into chunks

Posted on July 7, 2020

With a combination of `Array.prototype.map()` and `Array.prototpe.slice()`, we can split an array into many smaller arrays. This is useful for pagination or injecting something into an array every set number of elements. There’s an explanation of how this works on my blog: How to split arrays into equal-sized chunks

``````// `array` is the array we want to split, `chunkSize` is how big we want
// each group to be
const chunkArray = (array, chunkSize) => {
// find how many chunks we need if each holds `chunkSize` elements
const numberOfChunks = Math.ceil(array.length / chunkSize)

// create an array with one slot for each chunk we need
const chunks = [...Array(numberOfChunks)]
// walk through each of the empty slots
.map((value, index) => {
// put a slice of the original `array` in the empty slot
return array.slice(index * chunkSize, (index + 1) * chunkSize)
})

return chunks
}

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

console.log(chunkArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4))
// ⇒ [
//     [1, 2, 3, 4],
//     [5, 6, 7, 8],
//     [9, 10]
//   ]``````
``````// `array` is the array we want to split, `chunkSize` is how big we want
// each group to be
const chunkArray = (array, chunkSize) => {
// find how many chunks we need if each holds `chunkSize` elements
const numberOfChunks = Math.ceil(array.length / chunkSize)

// create an array with one slot for each chunk we need
const chunks = [...Array(numberOfChunks)]
// walk through each of the empty slots
.map((value, index) => {
// put a slice of the original `array` in the empty slot
return array.slice(index * chunkSize, (index + 1) * chunkSize)
})

return chunks
}

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

console.log(chunkArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4))
// ⇒ [
//     [1, 2, 3, 4],
//     [5, 6, 7, 8],
//     [9, 10]
//   ]``````

July 5, 2020JavaScript

## Logging as objects

This neat little trick makes values logged to the console much more readable with a minor adjustment to how we log it.

July 28, 2020JavaScript

## Getting the last element from an array

Until we get a native method on the array prototype itself, we can write a helper to get the last element in an array.

August 19, 2020JavaScript

## Removing the largest number from an array

To remove the largest value from an array of numbers we first need to find that number and can then filter it out.

July 17, 2020JavaScript

## Getting random elements from arrays

We can use the value returned by Math.random() to get a random element from an array.

July 11, 2020JavaScript

## Getting properties from objects that match a condition

Since array methods like filter and map return an array themselves, we can chain them one after the other.