How to split a long array into smaller arrays, with JavaScript


I have an array of e-mails (it can be just 1 email, or 100 emails), and I need to send the array with an ajax request (that I know how to do), but I can only send an array that has 10 or less e-mails in it. So if there is an original array of 20 e-mails I will need to split them up into 2 arrays of 10 each. or if there are 15 e-mails in the original array, then 1 array of 10, and another array of 5. I'm using jQuery, what would be the best way to do this?

This question is tagged with javascript jquery arrays loops

~ Asked on 2011-09-01 16:52:27

The Best Answer is


Don't use jquery...use plain javascript

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 could loop this to get the behavior you want.

var a = YOUR_ARRAY;
while(a.length) {

This would give you 10 elements at a time...if you have say 15 elements, you would get 1-10, the 11-15 as you wanted.

~ Answered on 2011-09-01 17:02:46


var size = 10; var arrayOfArrays = [];
for (var i=0; i<bigarray.length; i+=size) {

Unlike splice(), slice() is non-destructive to the original array.

~ Answered on 2011-09-01 16:56:12

Most Viewed Questions: