ReactHustle

How to Chunk an Array In Javascript or Typescript

Jasser Mark Arioste

Jasser Mark Arioste

How to Chunk an Array In Javascript or Typescript

Hello, hustlers! In this tutorial, you'll learn how to split an array into smaller chunks. First, we'll create a regular chunk function and try to improve it by extending the Array.prototype object in javascript.

How to Chunk a Javascript Array #

To chunk an array in javascript, one built-in method is particularly useful for this and that is Array.prototype.slice method.

This method returns a portion or slice of the array by accepting two optional arguments: start and end. These arguments represent the beginning and end of where to slice the array. It does not modify the original array.

const array = ["a", "b", "c", "d", "e"]
const sliced = array.slice(1,3)
console.log(sliced) // ["b", "c"]
123

Now that we know this, let's create a function that accepts an array and the number of items per chunk.

Javascript chunk() function #

function chunk(array, chunkSize) {
    const size = Math.ceil(array.length / chunkSize)
    const chunks = new Array(size).fill(0);
    return chunks.map((_, index) => {
        const start = index * chunkSize;
        const end = (index + 1) * chunkSize;
        return array.slice(start, end);
    })
}
123456789

Explanation:

In line 2, we identify the size of the chunk array by dividing the array length by the chunk size and then using the ceiling value. If your original array length is 10 and your chunk size is 4 that would be:

const size = Math.ceil(10/4)
size = Math.ciel(2.5) 
size = 3
12

In line 3, we create a new chunks array using the computed size, and fill it with temporary values of 0.

In lines 4-8, we map through the chunks array and return a new slice based on the index and chunkSize. To illustrate this more clearly, let's add some logs inside the map callback function.

function chunk(array, chunkSize) {
    const size = Math.ceil(array.length / chunkSize)
    const chunks = new Array(size).fill(0);
    return chunks.map((_, index) => {
        const start = index * chunkSize;
        const end = (index + 1) * chunkSize;
        const sliced = array.slice(start, end);
        console.log(start, end, sliced);
        return sliced;
    })
}
1234567891011

Here are the actual results:

// logs
// 0 4 [1, 2, 3, 4]
// 4 8 [5, 6, 7, 8]
// 8 12 [9, 10]
1234

Extending the Array.prototype object. #

If you use the chunk function often, it might make sense to extend the Array.prototype object so that all arrays will have access to the chunk function. Let's make some changes to our function:

Array.prototype.chunk = function (chunkSize) {
    const length = Math.ceil(this.length / chunkSize)
    const chunks = new Array(length).fill(0);
    return chunks.map((_, index) => {
        const start = index * chunkSize;
        const end = (index + 1) * chunkSize;
        return this.slice(start, end);
    })
}
123456789

Explanation

On line 1, we removed the first parameter array since we will now be using the this object to represent the array.

On lines 2 & 7, we modified all instances of array to this.

Now, we can simply do the following to chunk arrays:

const arr = [1,2,3,4,5,6,7,8,9,10];
const chunked = arr.chunk(4) // [[1,2,3,4],[5,6,7,8],[9,10]]
12

Typescript chunk function #

If you're using Typescript, which I think is better if you're building production apps, then here's the Typescript version of the chunk function:

function chunk<T>(array: T[], chunkSize:number) {
    const length = Math.ceil(array.length / chunkSize)
    const chunks = new Array(length).fill(0);
    return chunks.map((_, index) => {
        const start = index * chunkSize;
        const end = (index + 1) * chunkSize;
        return array.slice(start, end);
    })
}
123456789

Extending Array.prototype in Typescript #

To extend the Array.prototype object in Typescript, I suggest creating a separate file utils/array.extensions.ts. 


// First extend the Array.object types 
declare global {
  interface Array<T>  {
    chunk(chunkSize: number): T[][];
  }
}

// Do the implementation
if (!Array.prototype.chunk) {
  Array.prototype.chunk = function <T>( this: Array<T>, chunkSize: number): T[][] {
    const length = Math.ceil(this.length / chunkSize)
    const chunks = new Array(length).fill(0);
    return chunks.map((_, index) => {
        const start = index * chunkSize;
        const end = (index + 1) * chunkSize;
        return this.slice(start, end);
    })
  };
}

export {}
12345678910111213141516171819202122

Next, you can import this file on your index.ts:

const arr = [1,2,3,4,5,6,7,8,9,10];
const chunked = arr.chunk(4) // [[1,2,3,4],[5,6,7,8],[9,10]]
12

Conclusion #

You learned how to chunk javascript and typescript arrays by creating a chunk function and extending the Array.prototype object.

If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on GitHub.

Resources #

Credits: Image by Franz Roos from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle