Split an array into chunks in JavaScript
In this article, we have given a large array and we want to split it into chunks of smaller arrays in JavaScript. We have a few methods to do that such as:
- Using splice() Method
- Using slice() Method
Using 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.
Javascript
let i, j, chunk = 4; let arr = [1, 2, 3, 4, 5, 6, 7, 8]; let arr1 = arr.slice(0, chunk); let arr2 = arr.slice(chunk, chunk + arr.length); console.log( 'Array1: ' + arr1 + '\nArray2: ' + arr2); |
Array1: 1,2,3,4 Array2: 5,6,7,8
Using 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.
Javascript
let i, j, chunk = 2; let arr = [1, 2, 3, 4, 5, 6, 7, 8]; let arr1 = arr.splice(0, chunk); let arr2 = arr.splice(0, chunk); let arr3 = arr.splice(0, chunk); let arr4 = arr.splice(0, chunk); console.log( "Array1: " + arr1); console.log( "Array2: " + arr2); console.log( "Array3: " + arr3); console.log( "Array4: " + arr4); |
Array1: 1,2 Array2: 3,4 Array3: 5,6 Array4: 7,8
Please Login to comment...