Split an array into chunks in JavaScript
In this article, we have a large array and we want to split it into chunks of smaller arrays. We have a few methods to do that such as:
We will describe the above methods in detail below:
Javascript slice() method: This method returns a new array containing the selected elements. This method selects the elements starting from the given start argument, and ends at, but excluding the given end argument.
Syntax:
array.slice(start, end)
Example:This example uses the slice() method to split the array into chunks of the array. This method can be used repeatedly to split an array of any size.
html
<body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3>Using slice method()</h3> <p id="GFG_UP" style="font-size: 16px;"> </p> <button onclick="gfg_Run()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var i, j, chunk = 4; var array = [1, 2, 3, 4, 5, 6, 7, 8]; el_up.innerHTML = array; function gfg_Run() { var array1 = array.slice(0, chunk); var array2 = array.slice(chunk, chunk + array.length); el_down.innerHTML = array1 + ' and ' + array2; } </script></body> |
Output:
-method.gif)
Javascript splice() method: This method adds/removes items to/from an array, and returns the list of removed item(s).
Syntax:
array.splice(index, number, item1, ....., itemN)
Example: This example uses the splice() method to split the array into chunks of the array. This method removes the items from the original array. This method can be used repeatedly to split an array of any size.
html
<body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3>Using splice() method</h3> <p id="GFG_UP" style="font-size: 16px;"> </p> <button onclick="gfg_Run()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var i, j, chunk = 2; var array = [1, 2, 3, 4, 5, 6, 7, 8]; el_up.innerHTML = array; function gfg_Run() { var array1 = array.splice(0, chunk); var array2 = array.splice(0, chunk); var array3 = array.splice(0, chunk); var array4 = array.splice(0, chunk); el_down.innerHTML = array1 + ' | ' + array2 + ' | ' + array3 + ' | ' + array4; } </script></body> |
Output:
-method-2.gif)


Please Login to comment...