NodeJs How to Split/Splice Array in Chunks

Posted on September 9, 2019 at 2:56 pm

To split an array in chunks in NodeJs you can use splice():

var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var b = a.splice(0,10);
 
//a is now [11,12,13,14,15];
//b is now [1,2,3,4,5,6,7,8,9,10];

You can also loop the array and do something with the array chunk:

var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
 
while(a.length) {
    console.log(a.splice(0,10));
}

It should output like:

[1,2,3,4,5,6,7,8,9,10]
[11,12,13,14,15]

Receive updates via email

Other Posts

Updated Posts