Search code examples
javascriptjqueryarraysloops

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?


Solution

  • 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) {
        console.log(a.splice(0,10));
    }
    

    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.