Split an array into chunks of a given size in JavaScript

Created By Nikunj Kanetiya  |  Last Updated on : 2018-11-28

Objective

Looking for an easy way to split an array into chunks in javascript here is the simple snippet to do the same

Looking for an easy snippet to split the array in javascript? The most common case where I need it is when building the grids in vue.js, I often require splitting the array so that I can create row according to that.

/**
 * Returns an array with arrays of the given size.
 *
 * @param myArray {Array} Array to split
 * @param chunkSize {Integer} Size of every group
 */
function chunkArray(myArray, chunk_size) {
    let results = [];
    
    while (myArray.length) {
        results.push(myArray.splice(0, chunk_size))
    }

    return results;
}

// Usage

// Split in group of 3 items
var result = chunkArray([1,2,3,4,5,6,7,8], 3)

// Outputs : [ [1,2,3] , [4,5,6] ,[7,8] ]
console.log(result)
 
Created on : 2018-10-04
Written by

Nikunj Kanetiya

Full Stack Web Developer

Tags
Web Development
Javascript
Split javascript Array
Chuck array