This article will illustrate the procedure for splitting a long array into small arrays in JavaScript.
How to Split a Long Array Into Smaller Arrays With JavaScript?
For splitting a long array into small arrays, use the following methods:
Method 1: Split a Long Array Into Smaller Arrays Using slice() Method
Use the “slice()” method to split an array into smaller arrays. Without modifying the original array, it creates a new array with elements taken from the original array.
Syntax
Follow the given syntax for the slice() method:
In the above syntax:
- “start” is an integer that specifies the starting position of the slice/array. It is included in the slice.
- “end” is an integer that specifies the ending position of the slice/array. It is exclusive and is not included in the slice.
Example
Create an array of numbers:
Call the slice() method to get the slice of an array starting from index 0 to 5. Here the last index is exclusive:
console.log(array1);
The second slice will be from index 5 to index 8:
console.log(array2);
The last slice will be started from index 8, till the end:
console.log(array3);
The output indicates that the array has been successfully splitted into three different sizes arrays:
Now, we will split the array into different chunks by calling the function:
for (i=0; i<array.length; i += subArrays) {
var temp;
temp = array.slice(i, i + subArrays);
console.log(temp);
}
}
In the above code snippet:
- First, define a function named “splitArrayintoSubArrays” that takes two parameters “an array” and a “number of chunks” to divide the array.
- Iterate the whole array using the “for” loop.
- Call the slice() method to slice the array into chunks.
Create an array of numbers that will pass to the function for splitting into small arrays:
Specify the number of chunks that is “4”:
Call the defined function by passing array and the count of small arrays as arguments:
It can be seen that the output displays four small arrays, three of them are equal in size:
Method 2: Split a Long Array Into Smaller Arrays Using splice() Method
You can also use the “splice()” method for splitting an array into small arrays. It changes the original array by adding or removing elements and gives an array that contains the removed elements if any.
Syntax
The following syntax is utilized for the splice() method:
Example
Create a number array:
Call the splice() method by passing the start and the end count for the first smaller array:
Print the first chunk of an array:
Finally, print the remaining array:
Output
That’s all about splitting arrays into smaller arrays in JavaScript.
Conclusion
For splitting a long array into smaller arrays, use the “slice()” method or the “splice()” method. The slice() and splice() methods in JavaScript extract parts of an array but have different use cases and results. This article illustrated the procedure for splitting a long array into small arrays in JavaScript.