How to use splice() method In Javascript
splice() 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.
// Size of aaray chunks
let chunk = 2;
// Input array
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
// Splitted arrays
let arr1 = arr.splice(0, chunk);
let arr2 = arr.splice(0, chunk);
let arr3 = arr.splice(0, chunk);
let arr4 = arr.splice(0, chunk);
// Display output
console.log("Array1: " + arr1);
console.log("Array2: " + arr2);
console.log("Array3: " + arr3);
console.log("Array4: " + arr4);
Output
Array1: 1,2 Array2: 3,4 Array3: 5,6 Array4: 7,8
Split an array into chunks in JavaScript
Splitting an array into chunks in JavaScript involves dividing the array into smaller arrays of a specified size. This process is useful for managing large datasets more efficiently or for processing data in smaller, more manageable portions within the application.
Methods to split the array into chunks:
Table of Content
- Using JavaScript slice() method
- Using JavaScript splice() method
- Using Lodash _.chunk() Method
- Using a Loop to Split the Array
- Using Array.reduce():
- Using Array.from() and Array.splice()