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





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







62















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?










share|improve this question































    62















    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?










    share|improve this question



























      62












      62








      62


      26






      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?










      share|improve this question
















      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?







      javascript jquery arrays loops






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 25 '14 at 23:18









      David Thomas

      205k38300352




      205k38300352










      asked Sep 1 '11 at 16:52









      BillBill

      2,355115389




      2,355115389
























          15 Answers
          15






          active

          oldest

          votes


















          137














          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.






          share|improve this answer



















          • 4





            Note that YOUR_ARRAY will be consumed as well (array are objects...)

            – Claudio
            Sep 1 '11 at 17:08













          • Yeah, i was just putting that because a is non-descriptive, and I already wrote the example using a...it is a completely unnecessary line of code...Although, that makes me think...if using this pattern, you may want to do a deep copy into a working array as to not disrupt you original

            – jyore
            Sep 1 '11 at 17:12








          • 3





            I read slice instead of sPlice, now my browser is sad!

            – SpazzMarticus
            Nov 7 '16 at 12:03






          • 1





            1 liner, let b = a.map(() => a.splice(0,2)).filter(a => a)

            – junvar
            Aug 31 '18 at 18:49



















          75














          var size = 10; var arrayOfArrays = ;
          for (var i=0; i<bigarray.length; i+=size) {
          arrayOfArrays.push(bigarray.slice(i,i+size));
          }
          console.log(arrayOfArrays);


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






          share|improve this answer

































            26














            Just loop over the array, splicing it until it's all consumed.





            var a = ['a','b','c','d','e','f','g']
            , chunk

            while (a.length > 0) {

            chunk = a.splice(0,3)

            console.log(chunk)

            }



            output




            [ 'a', 'b', 'c' ]
            [ 'd', 'e', 'f' ]
            [ 'g' ]






            share|improve this answer































              24














              You can use lodash:
              https://lodash.com/docs



              _.chunk(['a', 'b', 'c', 'd'], 2);
              // → [['a', 'b'], ['c', 'd']]





              share|improve this answer































                9














                Assuming you don't want to destroy the original array, you can use code like this to break up the long array into smaller arrays which you can then iterate over:



                var longArray = ;   // assume this has 100 or more email addresses in it
                var shortArrays = , i, len;

                for (i = 0, len = longArray.length; i < len; i += 10) {
                shortArrays.push(longArray.slice(i, i + 10));
                }

                // now you can iterate over shortArrays which is an
                // array of arrays where each array has 10 or fewer
                // of the original email addresses in it

                for (i = 0, len = shortArrays.length; i < len; i++) {
                // shortArrays[i] is an array of email addresss of 10 or less
                }





                share|improve this answer































                  5














                  As a supplement to @jyore's answer, and in case you still want to keep the original array:



                  var originalArray = [1,2,3,4,5,6,7,8];

                  var splitArray = function (arr, size) {

                  var arr2 = arr.slice(0),
                  arrays = ;

                  while (arr2.length > 0) {
                  arrays.push(arr2.splice(0, size));
                  }

                  return arrays;
                  }

                  splitArray(originalArray, 2);
                  // originalArray is still = [1,2,3,4,5,6,7,8];





                  share|improve this answer

































                    3














                    Another method:



                    var longArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
                    var size = 2;

                    var newArray = new Array(Math.ceil(longArray.length / size)).fill("")
                    .map(function() { return this.splice(0, size) }, longArray.slice());

                    // newArray = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];


                    This doesn't affect the original array as a copy, made using slice, is passed into the 'this' argument of map.






                    share|improve this answer































                      3














                      Another implementation:



                      const arr = ["H", "o", "w", " ", "t", "o", " ", "s", "p", "l", "i", "t", " ", "a", " ", "l", "o", "n", "g", " ", "a", "r", "r", "a", "y", " ", "i", "n", "t", "o", " ", "s", "m", "a", "l", "l", "e", "r", " ", "a", "r", "r", "a", "y", "s", ",", " ", "w", "i", "t", "h", " ", "J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];

                      const size = 3;
                      const res = arr.reduce((acc, curr, i) => {
                      if ( !(i % size) ) { // if index is 0 or can be divided by the `size`...
                      acc.push(arr.slice(i, i + size)); // ..push a chunk of the original array to the accumulator
                      }
                      return acc;
                      }, );

                      // => [["H", "o", "w"], [" ", "t", "o"], [" ", "s", "p"], ["l", "i", "t"], [" ", "a", " "], ["l", "o", "n"], ["g", " ", "a"], ["r", "r", "a"], ["y", " ", "i"], ["n", "t", "o"], [" ", "s", "m"], ["a", "l", "l"], ["e", "r", " "], ["a", "r", "r"], ["a", "y", "s"], [",", " ", "w"], ["i", "t", "h"], [" ", "J", "a"], ["v", "a", "S"], ["c", "r", "i"], ["p", "t"]]


                      NB - This does not modify the original array.



                      Or, if you prefer a functional, immutable and self-contained method:



                      function splitBy(size, list) {
                      return list.reduce((acc, curr, i, self) => {
                      if ( !(i % size) ) {
                      return [
                      ...acc,
                      self.slice(i, i + size),
                      ];
                      }
                      return acc;
                      }, );
                      }





                      share|improve this answer

































                        3














                        I would like to share my solution as well. It's a little bit more verbose but works as well.



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

                        var chunksize = 4;


                        var chunks = ;

                        data.forEach((item)=>{
                        if(!chunks.length || chunks[chunks.length-1].length == chunksize)
                        chunks.push();

                        chunks[chunks.length-1].push(item);
                        });

                        console.log(chunks);


                        Output (formatted):



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





                        share|improve this answer































                          1














                          You can take a look at this code . Simple and Effective .



                          function chunkArrayInGroups(array, unit) {
                          var results = ,
                          length = Math.ceil(array.length / unit);

                          for (var i = 0; i < length; i++) {
                          results.push(array.slice(i * unit, (i + 1) * unit));
                          }
                          return results;
                          }

                          chunkArrayInGroups(["a", "b", "c", "d"], 2);





                          share|improve this answer































                            1














                            Another implementation, using Array.reduce (I think it’s the only one missing!):



                            const splitArray = (arr, size) =>
                            {
                            if (size === 0) {
                            return ;
                            }

                            return arr.reduce((split, element, index) => {
                            index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
                            return split;
                            }, );
                            };


                            As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if block is omitted you get an error, which might be what you want.






                            share|improve this answer































                              1














                              Here is a simple one liner






                              var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)
                              : (r.push([e]), r), ),
                              arr = Array.from({length: 31}).map((_,i) => i+1);
                              console.log(segment(arr,7));








                              share|improve this answer































                                0














                                If you want a method that doesn't modify the existing array, try this:



                                let oldArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
                                let newArray = ;
                                let size = 3; // Size of chunks you are after
                                let j = 0; // This helps us keep track of the child arrays

                                for (var i = 0; i < oldArray.length; i++) {
                                if (i % size === 0) {
                                j++
                                }
                                if(!newArray[j]) newArray[j] = ;
                                newArray[j].push(oldArray[i])
                                }





                                share|improve this answer































                                  0














                                  function chunkArrayInGroups(arr, size) {
                                  var newArr=;

                                  for (var i=0; arr.length>size; i++){
                                  newArr.push(arr.splice(0,size));
                                  }
                                  newArr.push(arr.slice(0));
                                  return newArr;

                                  }

                                  chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);





                                  share|improve this answer


























                                  • dont forget to make: newArr= a local variable

                                    – zgthompson
                                    Feb 25 '18 at 21:20











                                  • Code-only Answers tend to get flagged and then deleted for being Low Quality. Could you provide some commentary around how this solves the original problem?

                                    – Graham
                                    Feb 25 '18 at 21:57











                                  • this doesn't work if the chunk size is less than the input array size.

                                    – r3wt
                                    May 7 '18 at 19:30



















                                  0














                                  Array.reduce could be inefficient for large arrays, especially with the mod operator. I think a cleaner (and possibly easier to read) functional solution would be this:



                                  const chunkArray = (arr, size) =>
                                  arr.length > size
                                  ? [arr.slice(0, size), ...chunkArray(arr.slice(size), size)]
                                  : [arr];





                                  share|improve this answer
























                                    Your Answer






                                    StackExchange.ifUsing("editor", function () {
                                    StackExchange.using("externalEditor", function () {
                                    StackExchange.using("snippets", function () {
                                    StackExchange.snippets.init();
                                    });
                                    });
                                    }, "code-snippets");

                                    StackExchange.ready(function() {
                                    var channelOptions = {
                                    tags: "".split(" "),
                                    id: "1"
                                    };
                                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                    StackExchange.using("externalEditor", function() {
                                    // Have to fire editor after snippets, if snippets enabled
                                    if (StackExchange.settings.snippets.snippetsEnabled) {
                                    StackExchange.using("snippets", function() {
                                    createEditor();
                                    });
                                    }
                                    else {
                                    createEditor();
                                    }
                                    });

                                    function createEditor() {
                                    StackExchange.prepareEditor({
                                    heartbeatType: 'answer',
                                    autoActivateHeartbeat: false,
                                    convertImagesToLinks: true,
                                    noModals: true,
                                    showLowRepImageUploadWarning: true,
                                    reputationToPostImages: 10,
                                    bindNavPrevention: true,
                                    postfix: "",
                                    imageUploader: {
                                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                    allowUrls: true
                                    },
                                    onDemand: true,
                                    discardSelector: ".discard-answer"
                                    ,immediatelyShowMarkdownHelp:true
                                    });


                                    }
                                    });














                                    draft saved

                                    draft discarded


















                                    StackExchange.ready(
                                    function () {
                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7273668%2fhow-to-split-a-long-array-into-smaller-arrays-with-javascript%23new-answer', 'question_page');
                                    }
                                    );

                                    Post as a guest















                                    Required, but never shown

























                                    15 Answers
                                    15






                                    active

                                    oldest

                                    votes








                                    15 Answers
                                    15






                                    active

                                    oldest

                                    votes









                                    active

                                    oldest

                                    votes






                                    active

                                    oldest

                                    votes









                                    137














                                    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.






                                    share|improve this answer



















                                    • 4





                                      Note that YOUR_ARRAY will be consumed as well (array are objects...)

                                      – Claudio
                                      Sep 1 '11 at 17:08













                                    • Yeah, i was just putting that because a is non-descriptive, and I already wrote the example using a...it is a completely unnecessary line of code...Although, that makes me think...if using this pattern, you may want to do a deep copy into a working array as to not disrupt you original

                                      – jyore
                                      Sep 1 '11 at 17:12








                                    • 3





                                      I read slice instead of sPlice, now my browser is sad!

                                      – SpazzMarticus
                                      Nov 7 '16 at 12:03






                                    • 1





                                      1 liner, let b = a.map(() => a.splice(0,2)).filter(a => a)

                                      – junvar
                                      Aug 31 '18 at 18:49
















                                    137














                                    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.






                                    share|improve this answer



















                                    • 4





                                      Note that YOUR_ARRAY will be consumed as well (array are objects...)

                                      – Claudio
                                      Sep 1 '11 at 17:08













                                    • Yeah, i was just putting that because a is non-descriptive, and I already wrote the example using a...it is a completely unnecessary line of code...Although, that makes me think...if using this pattern, you may want to do a deep copy into a working array as to not disrupt you original

                                      – jyore
                                      Sep 1 '11 at 17:12








                                    • 3





                                      I read slice instead of sPlice, now my browser is sad!

                                      – SpazzMarticus
                                      Nov 7 '16 at 12:03






                                    • 1





                                      1 liner, let b = a.map(() => a.splice(0,2)).filter(a => a)

                                      – junvar
                                      Aug 31 '18 at 18:49














                                    137












                                    137








                                    137







                                    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.






                                    share|improve this answer













                                    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.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Sep 1 '11 at 17:02









                                    jyorejyore

                                    3,15421626




                                    3,15421626








                                    • 4





                                      Note that YOUR_ARRAY will be consumed as well (array are objects...)

                                      – Claudio
                                      Sep 1 '11 at 17:08













                                    • Yeah, i was just putting that because a is non-descriptive, and I already wrote the example using a...it is a completely unnecessary line of code...Although, that makes me think...if using this pattern, you may want to do a deep copy into a working array as to not disrupt you original

                                      – jyore
                                      Sep 1 '11 at 17:12








                                    • 3





                                      I read slice instead of sPlice, now my browser is sad!

                                      – SpazzMarticus
                                      Nov 7 '16 at 12:03






                                    • 1





                                      1 liner, let b = a.map(() => a.splice(0,2)).filter(a => a)

                                      – junvar
                                      Aug 31 '18 at 18:49














                                    • 4





                                      Note that YOUR_ARRAY will be consumed as well (array are objects...)

                                      – Claudio
                                      Sep 1 '11 at 17:08













                                    • Yeah, i was just putting that because a is non-descriptive, and I already wrote the example using a...it is a completely unnecessary line of code...Although, that makes me think...if using this pattern, you may want to do a deep copy into a working array as to not disrupt you original

                                      – jyore
                                      Sep 1 '11 at 17:12








                                    • 3





                                      I read slice instead of sPlice, now my browser is sad!

                                      – SpazzMarticus
                                      Nov 7 '16 at 12:03






                                    • 1





                                      1 liner, let b = a.map(() => a.splice(0,2)).filter(a => a)

                                      – junvar
                                      Aug 31 '18 at 18:49








                                    4




                                    4





                                    Note that YOUR_ARRAY will be consumed as well (array are objects...)

                                    – Claudio
                                    Sep 1 '11 at 17:08







                                    Note that YOUR_ARRAY will be consumed as well (array are objects...)

                                    – Claudio
                                    Sep 1 '11 at 17:08















                                    Yeah, i was just putting that because a is non-descriptive, and I already wrote the example using a...it is a completely unnecessary line of code...Although, that makes me think...if using this pattern, you may want to do a deep copy into a working array as to not disrupt you original

                                    – jyore
                                    Sep 1 '11 at 17:12







                                    Yeah, i was just putting that because a is non-descriptive, and I already wrote the example using a...it is a completely unnecessary line of code...Although, that makes me think...if using this pattern, you may want to do a deep copy into a working array as to not disrupt you original

                                    – jyore
                                    Sep 1 '11 at 17:12






                                    3




                                    3





                                    I read slice instead of sPlice, now my browser is sad!

                                    – SpazzMarticus
                                    Nov 7 '16 at 12:03





                                    I read slice instead of sPlice, now my browser is sad!

                                    – SpazzMarticus
                                    Nov 7 '16 at 12:03




                                    1




                                    1





                                    1 liner, let b = a.map(() => a.splice(0,2)).filter(a => a)

                                    – junvar
                                    Aug 31 '18 at 18:49





                                    1 liner, let b = a.map(() => a.splice(0,2)).filter(a => a)

                                    – junvar
                                    Aug 31 '18 at 18:49













                                    75














                                    var size = 10; var arrayOfArrays = ;
                                    for (var i=0; i<bigarray.length; i+=size) {
                                    arrayOfArrays.push(bigarray.slice(i,i+size));
                                    }
                                    console.log(arrayOfArrays);


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






                                    share|improve this answer






























                                      75














                                      var size = 10; var arrayOfArrays = ;
                                      for (var i=0; i<bigarray.length; i+=size) {
                                      arrayOfArrays.push(bigarray.slice(i,i+size));
                                      }
                                      console.log(arrayOfArrays);


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






                                      share|improve this answer




























                                        75












                                        75








                                        75







                                        var size = 10; var arrayOfArrays = ;
                                        for (var i=0; i<bigarray.length; i+=size) {
                                        arrayOfArrays.push(bigarray.slice(i,i+size));
                                        }
                                        console.log(arrayOfArrays);


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






                                        share|improve this answer















                                        var size = 10; var arrayOfArrays = ;
                                        for (var i=0; i<bigarray.length; i+=size) {
                                        arrayOfArrays.push(bigarray.slice(i,i+size));
                                        }
                                        console.log(arrayOfArrays);


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







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jul 19 '18 at 5:08









                                        IsmailS

                                        6,7841663122




                                        6,7841663122










                                        answered Sep 1 '11 at 16:56









                                        BlazemongerBlazemonger

                                        72.4k20116160




                                        72.4k20116160























                                            26














                                            Just loop over the array, splicing it until it's all consumed.





                                            var a = ['a','b','c','d','e','f','g']
                                            , chunk

                                            while (a.length > 0) {

                                            chunk = a.splice(0,3)

                                            console.log(chunk)

                                            }



                                            output




                                            [ 'a', 'b', 'c' ]
                                            [ 'd', 'e', 'f' ]
                                            [ 'g' ]






                                            share|improve this answer




























                                              26














                                              Just loop over the array, splicing it until it's all consumed.





                                              var a = ['a','b','c','d','e','f','g']
                                              , chunk

                                              while (a.length > 0) {

                                              chunk = a.splice(0,3)

                                              console.log(chunk)

                                              }



                                              output




                                              [ 'a', 'b', 'c' ]
                                              [ 'd', 'e', 'f' ]
                                              [ 'g' ]






                                              share|improve this answer


























                                                26












                                                26








                                                26







                                                Just loop over the array, splicing it until it's all consumed.





                                                var a = ['a','b','c','d','e','f','g']
                                                , chunk

                                                while (a.length > 0) {

                                                chunk = a.splice(0,3)

                                                console.log(chunk)

                                                }



                                                output




                                                [ 'a', 'b', 'c' ]
                                                [ 'd', 'e', 'f' ]
                                                [ 'g' ]






                                                share|improve this answer













                                                Just loop over the array, splicing it until it's all consumed.





                                                var a = ['a','b','c','d','e','f','g']
                                                , chunk

                                                while (a.length > 0) {

                                                chunk = a.splice(0,3)

                                                console.log(chunk)

                                                }



                                                output




                                                [ 'a', 'b', 'c' ]
                                                [ 'd', 'e', 'f' ]
                                                [ 'g' ]







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Sep 1 '11 at 16:59









                                                ClaudioClaudio

                                                2,71922435




                                                2,71922435























                                                    24














                                                    You can use lodash:
                                                    https://lodash.com/docs



                                                    _.chunk(['a', 'b', 'c', 'd'], 2);
                                                    // → [['a', 'b'], ['c', 'd']]





                                                    share|improve this answer




























                                                      24














                                                      You can use lodash:
                                                      https://lodash.com/docs



                                                      _.chunk(['a', 'b', 'c', 'd'], 2);
                                                      // → [['a', 'b'], ['c', 'd']]





                                                      share|improve this answer


























                                                        24












                                                        24








                                                        24







                                                        You can use lodash:
                                                        https://lodash.com/docs



                                                        _.chunk(['a', 'b', 'c', 'd'], 2);
                                                        // → [['a', 'b'], ['c', 'd']]





                                                        share|improve this answer













                                                        You can use lodash:
                                                        https://lodash.com/docs



                                                        _.chunk(['a', 'b', 'c', 'd'], 2);
                                                        // → [['a', 'b'], ['c', 'd']]






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Apr 7 '15 at 17:26









                                                        AlexParamonovAlexParamonov

                                                        924921




                                                        924921























                                                            9














                                                            Assuming you don't want to destroy the original array, you can use code like this to break up the long array into smaller arrays which you can then iterate over:



                                                            var longArray = ;   // assume this has 100 or more email addresses in it
                                                            var shortArrays = , i, len;

                                                            for (i = 0, len = longArray.length; i < len; i += 10) {
                                                            shortArrays.push(longArray.slice(i, i + 10));
                                                            }

                                                            // now you can iterate over shortArrays which is an
                                                            // array of arrays where each array has 10 or fewer
                                                            // of the original email addresses in it

                                                            for (i = 0, len = shortArrays.length; i < len; i++) {
                                                            // shortArrays[i] is an array of email addresss of 10 or less
                                                            }





                                                            share|improve this answer




























                                                              9














                                                              Assuming you don't want to destroy the original array, you can use code like this to break up the long array into smaller arrays which you can then iterate over:



                                                              var longArray = ;   // assume this has 100 or more email addresses in it
                                                              var shortArrays = , i, len;

                                                              for (i = 0, len = longArray.length; i < len; i += 10) {
                                                              shortArrays.push(longArray.slice(i, i + 10));
                                                              }

                                                              // now you can iterate over shortArrays which is an
                                                              // array of arrays where each array has 10 or fewer
                                                              // of the original email addresses in it

                                                              for (i = 0, len = shortArrays.length; i < len; i++) {
                                                              // shortArrays[i] is an array of email addresss of 10 or less
                                                              }





                                                              share|improve this answer


























                                                                9












                                                                9








                                                                9







                                                                Assuming you don't want to destroy the original array, you can use code like this to break up the long array into smaller arrays which you can then iterate over:



                                                                var longArray = ;   // assume this has 100 or more email addresses in it
                                                                var shortArrays = , i, len;

                                                                for (i = 0, len = longArray.length; i < len; i += 10) {
                                                                shortArrays.push(longArray.slice(i, i + 10));
                                                                }

                                                                // now you can iterate over shortArrays which is an
                                                                // array of arrays where each array has 10 or fewer
                                                                // of the original email addresses in it

                                                                for (i = 0, len = shortArrays.length; i < len; i++) {
                                                                // shortArrays[i] is an array of email addresss of 10 or less
                                                                }





                                                                share|improve this answer













                                                                Assuming you don't want to destroy the original array, you can use code like this to break up the long array into smaller arrays which you can then iterate over:



                                                                var longArray = ;   // assume this has 100 or more email addresses in it
                                                                var shortArrays = , i, len;

                                                                for (i = 0, len = longArray.length; i < len; i += 10) {
                                                                shortArrays.push(longArray.slice(i, i + 10));
                                                                }

                                                                // now you can iterate over shortArrays which is an
                                                                // array of arrays where each array has 10 or fewer
                                                                // of the original email addresses in it

                                                                for (i = 0, len = shortArrays.length; i < len; i++) {
                                                                // shortArrays[i] is an array of email addresss of 10 or less
                                                                }






                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Sep 1 '11 at 17:00









                                                                jfriend00jfriend00

                                                                441k55581624




                                                                441k55581624























                                                                    5














                                                                    As a supplement to @jyore's answer, and in case you still want to keep the original array:



                                                                    var originalArray = [1,2,3,4,5,6,7,8];

                                                                    var splitArray = function (arr, size) {

                                                                    var arr2 = arr.slice(0),
                                                                    arrays = ;

                                                                    while (arr2.length > 0) {
                                                                    arrays.push(arr2.splice(0, size));
                                                                    }

                                                                    return arrays;
                                                                    }

                                                                    splitArray(originalArray, 2);
                                                                    // originalArray is still = [1,2,3,4,5,6,7,8];





                                                                    share|improve this answer






























                                                                      5














                                                                      As a supplement to @jyore's answer, and in case you still want to keep the original array:



                                                                      var originalArray = [1,2,3,4,5,6,7,8];

                                                                      var splitArray = function (arr, size) {

                                                                      var arr2 = arr.slice(0),
                                                                      arrays = ;

                                                                      while (arr2.length > 0) {
                                                                      arrays.push(arr2.splice(0, size));
                                                                      }

                                                                      return arrays;
                                                                      }

                                                                      splitArray(originalArray, 2);
                                                                      // originalArray is still = [1,2,3,4,5,6,7,8];





                                                                      share|improve this answer




























                                                                        5












                                                                        5








                                                                        5







                                                                        As a supplement to @jyore's answer, and in case you still want to keep the original array:



                                                                        var originalArray = [1,2,3,4,5,6,7,8];

                                                                        var splitArray = function (arr, size) {

                                                                        var arr2 = arr.slice(0),
                                                                        arrays = ;

                                                                        while (arr2.length > 0) {
                                                                        arrays.push(arr2.splice(0, size));
                                                                        }

                                                                        return arrays;
                                                                        }

                                                                        splitArray(originalArray, 2);
                                                                        // originalArray is still = [1,2,3,4,5,6,7,8];





                                                                        share|improve this answer















                                                                        As a supplement to @jyore's answer, and in case you still want to keep the original array:



                                                                        var originalArray = [1,2,3,4,5,6,7,8];

                                                                        var splitArray = function (arr, size) {

                                                                        var arr2 = arr.slice(0),
                                                                        arrays = ;

                                                                        while (arr2.length > 0) {
                                                                        arrays.push(arr2.splice(0, size));
                                                                        }

                                                                        return arrays;
                                                                        }

                                                                        splitArray(originalArray, 2);
                                                                        // originalArray is still = [1,2,3,4,5,6,7,8];






                                                                        share|improve this answer














                                                                        share|improve this answer



                                                                        share|improve this answer








                                                                        edited May 23 '17 at 11:47









                                                                        Community

                                                                        11




                                                                        11










                                                                        answered Nov 30 '14 at 20:47









                                                                        JustinJustin

                                                                        1,03821321




                                                                        1,03821321























                                                                            3














                                                                            Another method:



                                                                            var longArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
                                                                            var size = 2;

                                                                            var newArray = new Array(Math.ceil(longArray.length / size)).fill("")
                                                                            .map(function() { return this.splice(0, size) }, longArray.slice());

                                                                            // newArray = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];


                                                                            This doesn't affect the original array as a copy, made using slice, is passed into the 'this' argument of map.






                                                                            share|improve this answer




























                                                                              3














                                                                              Another method:



                                                                              var longArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
                                                                              var size = 2;

                                                                              var newArray = new Array(Math.ceil(longArray.length / size)).fill("")
                                                                              .map(function() { return this.splice(0, size) }, longArray.slice());

                                                                              // newArray = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];


                                                                              This doesn't affect the original array as a copy, made using slice, is passed into the 'this' argument of map.






                                                                              share|improve this answer


























                                                                                3












                                                                                3








                                                                                3







                                                                                Another method:



                                                                                var longArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
                                                                                var size = 2;

                                                                                var newArray = new Array(Math.ceil(longArray.length / size)).fill("")
                                                                                .map(function() { return this.splice(0, size) }, longArray.slice());

                                                                                // newArray = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];


                                                                                This doesn't affect the original array as a copy, made using slice, is passed into the 'this' argument of map.






                                                                                share|improve this answer













                                                                                Another method:



                                                                                var longArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
                                                                                var size = 2;

                                                                                var newArray = new Array(Math.ceil(longArray.length / size)).fill("")
                                                                                .map(function() { return this.splice(0, size) }, longArray.slice());

                                                                                // newArray = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];


                                                                                This doesn't affect the original array as a copy, made using slice, is passed into the 'this' argument of map.







                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Mar 8 '17 at 16:09









                                                                                AFurlepaAFurlepa

                                                                                314




                                                                                314























                                                                                    3














                                                                                    Another implementation:



                                                                                    const arr = ["H", "o", "w", " ", "t", "o", " ", "s", "p", "l", "i", "t", " ", "a", " ", "l", "o", "n", "g", " ", "a", "r", "r", "a", "y", " ", "i", "n", "t", "o", " ", "s", "m", "a", "l", "l", "e", "r", " ", "a", "r", "r", "a", "y", "s", ",", " ", "w", "i", "t", "h", " ", "J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];

                                                                                    const size = 3;
                                                                                    const res = arr.reduce((acc, curr, i) => {
                                                                                    if ( !(i % size) ) { // if index is 0 or can be divided by the `size`...
                                                                                    acc.push(arr.slice(i, i + size)); // ..push a chunk of the original array to the accumulator
                                                                                    }
                                                                                    return acc;
                                                                                    }, );

                                                                                    // => [["H", "o", "w"], [" ", "t", "o"], [" ", "s", "p"], ["l", "i", "t"], [" ", "a", " "], ["l", "o", "n"], ["g", " ", "a"], ["r", "r", "a"], ["y", " ", "i"], ["n", "t", "o"], [" ", "s", "m"], ["a", "l", "l"], ["e", "r", " "], ["a", "r", "r"], ["a", "y", "s"], [",", " ", "w"], ["i", "t", "h"], [" ", "J", "a"], ["v", "a", "S"], ["c", "r", "i"], ["p", "t"]]


                                                                                    NB - This does not modify the original array.



                                                                                    Or, if you prefer a functional, immutable and self-contained method:



                                                                                    function splitBy(size, list) {
                                                                                    return list.reduce((acc, curr, i, self) => {
                                                                                    if ( !(i % size) ) {
                                                                                    return [
                                                                                    ...acc,
                                                                                    self.slice(i, i + size),
                                                                                    ];
                                                                                    }
                                                                                    return acc;
                                                                                    }, );
                                                                                    }





                                                                                    share|improve this answer






























                                                                                      3














                                                                                      Another implementation:



                                                                                      const arr = ["H", "o", "w", " ", "t", "o", " ", "s", "p", "l", "i", "t", " ", "a", " ", "l", "o", "n", "g", " ", "a", "r", "r", "a", "y", " ", "i", "n", "t", "o", " ", "s", "m", "a", "l", "l", "e", "r", " ", "a", "r", "r", "a", "y", "s", ",", " ", "w", "i", "t", "h", " ", "J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];

                                                                                      const size = 3;
                                                                                      const res = arr.reduce((acc, curr, i) => {
                                                                                      if ( !(i % size) ) { // if index is 0 or can be divided by the `size`...
                                                                                      acc.push(arr.slice(i, i + size)); // ..push a chunk of the original array to the accumulator
                                                                                      }
                                                                                      return acc;
                                                                                      }, );

                                                                                      // => [["H", "o", "w"], [" ", "t", "o"], [" ", "s", "p"], ["l", "i", "t"], [" ", "a", " "], ["l", "o", "n"], ["g", " ", "a"], ["r", "r", "a"], ["y", " ", "i"], ["n", "t", "o"], [" ", "s", "m"], ["a", "l", "l"], ["e", "r", " "], ["a", "r", "r"], ["a", "y", "s"], [",", " ", "w"], ["i", "t", "h"], [" ", "J", "a"], ["v", "a", "S"], ["c", "r", "i"], ["p", "t"]]


                                                                                      NB - This does not modify the original array.



                                                                                      Or, if you prefer a functional, immutable and self-contained method:



                                                                                      function splitBy(size, list) {
                                                                                      return list.reduce((acc, curr, i, self) => {
                                                                                      if ( !(i % size) ) {
                                                                                      return [
                                                                                      ...acc,
                                                                                      self.slice(i, i + size),
                                                                                      ];
                                                                                      }
                                                                                      return acc;
                                                                                      }, );
                                                                                      }





                                                                                      share|improve this answer




























                                                                                        3












                                                                                        3








                                                                                        3







                                                                                        Another implementation:



                                                                                        const arr = ["H", "o", "w", " ", "t", "o", " ", "s", "p", "l", "i", "t", " ", "a", " ", "l", "o", "n", "g", " ", "a", "r", "r", "a", "y", " ", "i", "n", "t", "o", " ", "s", "m", "a", "l", "l", "e", "r", " ", "a", "r", "r", "a", "y", "s", ",", " ", "w", "i", "t", "h", " ", "J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];

                                                                                        const size = 3;
                                                                                        const res = arr.reduce((acc, curr, i) => {
                                                                                        if ( !(i % size) ) { // if index is 0 or can be divided by the `size`...
                                                                                        acc.push(arr.slice(i, i + size)); // ..push a chunk of the original array to the accumulator
                                                                                        }
                                                                                        return acc;
                                                                                        }, );

                                                                                        // => [["H", "o", "w"], [" ", "t", "o"], [" ", "s", "p"], ["l", "i", "t"], [" ", "a", " "], ["l", "o", "n"], ["g", " ", "a"], ["r", "r", "a"], ["y", " ", "i"], ["n", "t", "o"], [" ", "s", "m"], ["a", "l", "l"], ["e", "r", " "], ["a", "r", "r"], ["a", "y", "s"], [",", " ", "w"], ["i", "t", "h"], [" ", "J", "a"], ["v", "a", "S"], ["c", "r", "i"], ["p", "t"]]


                                                                                        NB - This does not modify the original array.



                                                                                        Or, if you prefer a functional, immutable and self-contained method:



                                                                                        function splitBy(size, list) {
                                                                                        return list.reduce((acc, curr, i, self) => {
                                                                                        if ( !(i % size) ) {
                                                                                        return [
                                                                                        ...acc,
                                                                                        self.slice(i, i + size),
                                                                                        ];
                                                                                        }
                                                                                        return acc;
                                                                                        }, );
                                                                                        }





                                                                                        share|improve this answer















                                                                                        Another implementation:



                                                                                        const arr = ["H", "o", "w", " ", "t", "o", " ", "s", "p", "l", "i", "t", " ", "a", " ", "l", "o", "n", "g", " ", "a", "r", "r", "a", "y", " ", "i", "n", "t", "o", " ", "s", "m", "a", "l", "l", "e", "r", " ", "a", "r", "r", "a", "y", "s", ",", " ", "w", "i", "t", "h", " ", "J", "a", "v", "a", "S", "c", "r", "i", "p", "t"];

                                                                                        const size = 3;
                                                                                        const res = arr.reduce((acc, curr, i) => {
                                                                                        if ( !(i % size) ) { // if index is 0 or can be divided by the `size`...
                                                                                        acc.push(arr.slice(i, i + size)); // ..push a chunk of the original array to the accumulator
                                                                                        }
                                                                                        return acc;
                                                                                        }, );

                                                                                        // => [["H", "o", "w"], [" ", "t", "o"], [" ", "s", "p"], ["l", "i", "t"], [" ", "a", " "], ["l", "o", "n"], ["g", " ", "a"], ["r", "r", "a"], ["y", " ", "i"], ["n", "t", "o"], [" ", "s", "m"], ["a", "l", "l"], ["e", "r", " "], ["a", "r", "r"], ["a", "y", "s"], [",", " ", "w"], ["i", "t", "h"], [" ", "J", "a"], ["v", "a", "S"], ["c", "r", "i"], ["p", "t"]]


                                                                                        NB - This does not modify the original array.



                                                                                        Or, if you prefer a functional, immutable and self-contained method:



                                                                                        function splitBy(size, list) {
                                                                                        return list.reduce((acc, curr, i, self) => {
                                                                                        if ( !(i % size) ) {
                                                                                        return [
                                                                                        ...acc,
                                                                                        self.slice(i, i + size),
                                                                                        ];
                                                                                        }
                                                                                        return acc;
                                                                                        }, );
                                                                                        }






                                                                                        share|improve this answer














                                                                                        share|improve this answer



                                                                                        share|improve this answer








                                                                                        edited May 24 '17 at 11:38

























                                                                                        answered Sep 30 '16 at 23:12









                                                                                        NobitaNobita

                                                                                        14k64458




                                                                                        14k64458























                                                                                            3














                                                                                            I would like to share my solution as well. It's a little bit more verbose but works as well.



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

                                                                                            var chunksize = 4;


                                                                                            var chunks = ;

                                                                                            data.forEach((item)=>{
                                                                                            if(!chunks.length || chunks[chunks.length-1].length == chunksize)
                                                                                            chunks.push();

                                                                                            chunks[chunks.length-1].push(item);
                                                                                            });

                                                                                            console.log(chunks);


                                                                                            Output (formatted):



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





                                                                                            share|improve this answer




























                                                                                              3














                                                                                              I would like to share my solution as well. It's a little bit more verbose but works as well.



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

                                                                                              var chunksize = 4;


                                                                                              var chunks = ;

                                                                                              data.forEach((item)=>{
                                                                                              if(!chunks.length || chunks[chunks.length-1].length == chunksize)
                                                                                              chunks.push();

                                                                                              chunks[chunks.length-1].push(item);
                                                                                              });

                                                                                              console.log(chunks);


                                                                                              Output (formatted):



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





                                                                                              share|improve this answer


























                                                                                                3












                                                                                                3








                                                                                                3







                                                                                                I would like to share my solution as well. It's a little bit more verbose but works as well.



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

                                                                                                var chunksize = 4;


                                                                                                var chunks = ;

                                                                                                data.forEach((item)=>{
                                                                                                if(!chunks.length || chunks[chunks.length-1].length == chunksize)
                                                                                                chunks.push();

                                                                                                chunks[chunks.length-1].push(item);
                                                                                                });

                                                                                                console.log(chunks);


                                                                                                Output (formatted):



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





                                                                                                share|improve this answer













                                                                                                I would like to share my solution as well. It's a little bit more verbose but works as well.



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

                                                                                                var chunksize = 4;


                                                                                                var chunks = ;

                                                                                                data.forEach((item)=>{
                                                                                                if(!chunks.length || chunks[chunks.length-1].length == chunksize)
                                                                                                chunks.push();

                                                                                                chunks[chunks.length-1].push(item);
                                                                                                });

                                                                                                console.log(chunks);


                                                                                                Output (formatted):



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






                                                                                                share|improve this answer












                                                                                                share|improve this answer



                                                                                                share|improve this answer










                                                                                                answered Oct 27 '17 at 12:09









                                                                                                Filipe NicoliFilipe Nicoli

                                                                                                13816




                                                                                                13816























                                                                                                    1














                                                                                                    You can take a look at this code . Simple and Effective .



                                                                                                    function chunkArrayInGroups(array, unit) {
                                                                                                    var results = ,
                                                                                                    length = Math.ceil(array.length / unit);

                                                                                                    for (var i = 0; i < length; i++) {
                                                                                                    results.push(array.slice(i * unit, (i + 1) * unit));
                                                                                                    }
                                                                                                    return results;
                                                                                                    }

                                                                                                    chunkArrayInGroups(["a", "b", "c", "d"], 2);





                                                                                                    share|improve this answer




























                                                                                                      1














                                                                                                      You can take a look at this code . Simple and Effective .



                                                                                                      function chunkArrayInGroups(array, unit) {
                                                                                                      var results = ,
                                                                                                      length = Math.ceil(array.length / unit);

                                                                                                      for (var i = 0; i < length; i++) {
                                                                                                      results.push(array.slice(i * unit, (i + 1) * unit));
                                                                                                      }
                                                                                                      return results;
                                                                                                      }

                                                                                                      chunkArrayInGroups(["a", "b", "c", "d"], 2);





                                                                                                      share|improve this answer


























                                                                                                        1












                                                                                                        1








                                                                                                        1







                                                                                                        You can take a look at this code . Simple and Effective .



                                                                                                        function chunkArrayInGroups(array, unit) {
                                                                                                        var results = ,
                                                                                                        length = Math.ceil(array.length / unit);

                                                                                                        for (var i = 0; i < length; i++) {
                                                                                                        results.push(array.slice(i * unit, (i + 1) * unit));
                                                                                                        }
                                                                                                        return results;
                                                                                                        }

                                                                                                        chunkArrayInGroups(["a", "b", "c", "d"], 2);





                                                                                                        share|improve this answer













                                                                                                        You can take a look at this code . Simple and Effective .



                                                                                                        function chunkArrayInGroups(array, unit) {
                                                                                                        var results = ,
                                                                                                        length = Math.ceil(array.length / unit);

                                                                                                        for (var i = 0; i < length; i++) {
                                                                                                        results.push(array.slice(i * unit, (i + 1) * unit));
                                                                                                        }
                                                                                                        return results;
                                                                                                        }

                                                                                                        chunkArrayInGroups(["a", "b", "c", "d"], 2);






                                                                                                        share|improve this answer












                                                                                                        share|improve this answer



                                                                                                        share|improve this answer










                                                                                                        answered Mar 29 '16 at 13:41









                                                                                                        SubhankarSubhankar

                                                                                                        112




                                                                                                        112























                                                                                                            1














                                                                                                            Another implementation, using Array.reduce (I think it’s the only one missing!):



                                                                                                            const splitArray = (arr, size) =>
                                                                                                            {
                                                                                                            if (size === 0) {
                                                                                                            return ;
                                                                                                            }

                                                                                                            return arr.reduce((split, element, index) => {
                                                                                                            index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
                                                                                                            return split;
                                                                                                            }, );
                                                                                                            };


                                                                                                            As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if block is omitted you get an error, which might be what you want.






                                                                                                            share|improve this answer




























                                                                                                              1














                                                                                                              Another implementation, using Array.reduce (I think it’s the only one missing!):



                                                                                                              const splitArray = (arr, size) =>
                                                                                                              {
                                                                                                              if (size === 0) {
                                                                                                              return ;
                                                                                                              }

                                                                                                              return arr.reduce((split, element, index) => {
                                                                                                              index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
                                                                                                              return split;
                                                                                                              }, );
                                                                                                              };


                                                                                                              As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if block is omitted you get an error, which might be what you want.






                                                                                                              share|improve this answer


























                                                                                                                1












                                                                                                                1








                                                                                                                1







                                                                                                                Another implementation, using Array.reduce (I think it’s the only one missing!):



                                                                                                                const splitArray = (arr, size) =>
                                                                                                                {
                                                                                                                if (size === 0) {
                                                                                                                return ;
                                                                                                                }

                                                                                                                return arr.reduce((split, element, index) => {
                                                                                                                index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
                                                                                                                return split;
                                                                                                                }, );
                                                                                                                };


                                                                                                                As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if block is omitted you get an error, which might be what you want.






                                                                                                                share|improve this answer













                                                                                                                Another implementation, using Array.reduce (I think it’s the only one missing!):



                                                                                                                const splitArray = (arr, size) =>
                                                                                                                {
                                                                                                                if (size === 0) {
                                                                                                                return ;
                                                                                                                }

                                                                                                                return arr.reduce((split, element, index) => {
                                                                                                                index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
                                                                                                                return split;
                                                                                                                }, );
                                                                                                                };


                                                                                                                As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if block is omitted you get an error, which might be what you want.







                                                                                                                share|improve this answer












                                                                                                                share|improve this answer



                                                                                                                share|improve this answer










                                                                                                                answered Apr 18 '17 at 10:01









                                                                                                                AlfAlf

                                                                                                                8111024




                                                                                                                8111024























                                                                                                                    1














                                                                                                                    Here is a simple one liner






                                                                                                                    var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)
                                                                                                                    : (r.push([e]), r), ),
                                                                                                                    arr = Array.from({length: 31}).map((_,i) => i+1);
                                                                                                                    console.log(segment(arr,7));








                                                                                                                    share|improve this answer




























                                                                                                                      1














                                                                                                                      Here is a simple one liner






                                                                                                                      var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)
                                                                                                                      : (r.push([e]), r), ),
                                                                                                                      arr = Array.from({length: 31}).map((_,i) => i+1);
                                                                                                                      console.log(segment(arr,7));








                                                                                                                      share|improve this answer


























                                                                                                                        1












                                                                                                                        1








                                                                                                                        1







                                                                                                                        Here is a simple one liner






                                                                                                                        var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)
                                                                                                                        : (r.push([e]), r), ),
                                                                                                                        arr = Array.from({length: 31}).map((_,i) => i+1);
                                                                                                                        console.log(segment(arr,7));








                                                                                                                        share|improve this answer













                                                                                                                        Here is a simple one liner






                                                                                                                        var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)
                                                                                                                        : (r.push([e]), r), ),
                                                                                                                        arr = Array.from({length: 31}).map((_,i) => i+1);
                                                                                                                        console.log(segment(arr,7));








                                                                                                                        var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)
                                                                                                                        : (r.push([e]), r), ),
                                                                                                                        arr = Array.from({length: 31}).map((_,i) => i+1);
                                                                                                                        console.log(segment(arr,7));





                                                                                                                        var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)
                                                                                                                        : (r.push([e]), r), ),
                                                                                                                        arr = Array.from({length: 31}).map((_,i) => i+1);
                                                                                                                        console.log(segment(arr,7));






                                                                                                                        share|improve this answer












                                                                                                                        share|improve this answer



                                                                                                                        share|improve this answer










                                                                                                                        answered May 23 '17 at 11:43









                                                                                                                        ReduRedu

                                                                                                                        13.2k22537




                                                                                                                        13.2k22537























                                                                                                                            0














                                                                                                                            If you want a method that doesn't modify the existing array, try this:



                                                                                                                            let oldArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
                                                                                                                            let newArray = ;
                                                                                                                            let size = 3; // Size of chunks you are after
                                                                                                                            let j = 0; // This helps us keep track of the child arrays

                                                                                                                            for (var i = 0; i < oldArray.length; i++) {
                                                                                                                            if (i % size === 0) {
                                                                                                                            j++
                                                                                                                            }
                                                                                                                            if(!newArray[j]) newArray[j] = ;
                                                                                                                            newArray[j].push(oldArray[i])
                                                                                                                            }





                                                                                                                            share|improve this answer




























                                                                                                                              0














                                                                                                                              If you want a method that doesn't modify the existing array, try this:



                                                                                                                              let oldArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
                                                                                                                              let newArray = ;
                                                                                                                              let size = 3; // Size of chunks you are after
                                                                                                                              let j = 0; // This helps us keep track of the child arrays

                                                                                                                              for (var i = 0; i < oldArray.length; i++) {
                                                                                                                              if (i % size === 0) {
                                                                                                                              j++
                                                                                                                              }
                                                                                                                              if(!newArray[j]) newArray[j] = ;
                                                                                                                              newArray[j].push(oldArray[i])
                                                                                                                              }





                                                                                                                              share|improve this answer


























                                                                                                                                0












                                                                                                                                0








                                                                                                                                0







                                                                                                                                If you want a method that doesn't modify the existing array, try this:



                                                                                                                                let oldArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
                                                                                                                                let newArray = ;
                                                                                                                                let size = 3; // Size of chunks you are after
                                                                                                                                let j = 0; // This helps us keep track of the child arrays

                                                                                                                                for (var i = 0; i < oldArray.length; i++) {
                                                                                                                                if (i % size === 0) {
                                                                                                                                j++
                                                                                                                                }
                                                                                                                                if(!newArray[j]) newArray[j] = ;
                                                                                                                                newArray[j].push(oldArray[i])
                                                                                                                                }





                                                                                                                                share|improve this answer













                                                                                                                                If you want a method that doesn't modify the existing array, try this:



                                                                                                                                let oldArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
                                                                                                                                let newArray = ;
                                                                                                                                let size = 3; // Size of chunks you are after
                                                                                                                                let j = 0; // This helps us keep track of the child arrays

                                                                                                                                for (var i = 0; i < oldArray.length; i++) {
                                                                                                                                if (i % size === 0) {
                                                                                                                                j++
                                                                                                                                }
                                                                                                                                if(!newArray[j]) newArray[j] = ;
                                                                                                                                newArray[j].push(oldArray[i])
                                                                                                                                }






                                                                                                                                share|improve this answer












                                                                                                                                share|improve this answer



                                                                                                                                share|improve this answer










                                                                                                                                answered Jul 27 '16 at 0:10









                                                                                                                                RyanRyan

                                                                                                                                6231817




                                                                                                                                6231817























                                                                                                                                    0














                                                                                                                                    function chunkArrayInGroups(arr, size) {
                                                                                                                                    var newArr=;

                                                                                                                                    for (var i=0; arr.length>size; i++){
                                                                                                                                    newArr.push(arr.splice(0,size));
                                                                                                                                    }
                                                                                                                                    newArr.push(arr.slice(0));
                                                                                                                                    return newArr;

                                                                                                                                    }

                                                                                                                                    chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);





                                                                                                                                    share|improve this answer


























                                                                                                                                    • dont forget to make: newArr= a local variable

                                                                                                                                      – zgthompson
                                                                                                                                      Feb 25 '18 at 21:20











                                                                                                                                    • Code-only Answers tend to get flagged and then deleted for being Low Quality. Could you provide some commentary around how this solves the original problem?

                                                                                                                                      – Graham
                                                                                                                                      Feb 25 '18 at 21:57











                                                                                                                                    • this doesn't work if the chunk size is less than the input array size.

                                                                                                                                      – r3wt
                                                                                                                                      May 7 '18 at 19:30
















                                                                                                                                    0














                                                                                                                                    function chunkArrayInGroups(arr, size) {
                                                                                                                                    var newArr=;

                                                                                                                                    for (var i=0; arr.length>size; i++){
                                                                                                                                    newArr.push(arr.splice(0,size));
                                                                                                                                    }
                                                                                                                                    newArr.push(arr.slice(0));
                                                                                                                                    return newArr;

                                                                                                                                    }

                                                                                                                                    chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);





                                                                                                                                    share|improve this answer


























                                                                                                                                    • dont forget to make: newArr= a local variable

                                                                                                                                      – zgthompson
                                                                                                                                      Feb 25 '18 at 21:20











                                                                                                                                    • Code-only Answers tend to get flagged and then deleted for being Low Quality. Could you provide some commentary around how this solves the original problem?

                                                                                                                                      – Graham
                                                                                                                                      Feb 25 '18 at 21:57











                                                                                                                                    • this doesn't work if the chunk size is less than the input array size.

                                                                                                                                      – r3wt
                                                                                                                                      May 7 '18 at 19:30














                                                                                                                                    0












                                                                                                                                    0








                                                                                                                                    0







                                                                                                                                    function chunkArrayInGroups(arr, size) {
                                                                                                                                    var newArr=;

                                                                                                                                    for (var i=0; arr.length>size; i++){
                                                                                                                                    newArr.push(arr.splice(0,size));
                                                                                                                                    }
                                                                                                                                    newArr.push(arr.slice(0));
                                                                                                                                    return newArr;

                                                                                                                                    }

                                                                                                                                    chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);





                                                                                                                                    share|improve this answer















                                                                                                                                    function chunkArrayInGroups(arr, size) {
                                                                                                                                    var newArr=;

                                                                                                                                    for (var i=0; arr.length>size; i++){
                                                                                                                                    newArr.push(arr.splice(0,size));
                                                                                                                                    }
                                                                                                                                    newArr.push(arr.slice(0));
                                                                                                                                    return newArr;

                                                                                                                                    }

                                                                                                                                    chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3);






                                                                                                                                    share|improve this answer














                                                                                                                                    share|improve this answer



                                                                                                                                    share|improve this answer








                                                                                                                                    edited Feb 25 '18 at 21:24









                                                                                                                                    Vega

                                                                                                                                    14.4k113961




                                                                                                                                    14.4k113961










                                                                                                                                    answered Feb 25 '18 at 21:19









                                                                                                                                    zgthompsonzgthompson

                                                                                                                                    112




                                                                                                                                    112













                                                                                                                                    • dont forget to make: newArr= a local variable

                                                                                                                                      – zgthompson
                                                                                                                                      Feb 25 '18 at 21:20











                                                                                                                                    • Code-only Answers tend to get flagged and then deleted for being Low Quality. Could you provide some commentary around how this solves the original problem?

                                                                                                                                      – Graham
                                                                                                                                      Feb 25 '18 at 21:57











                                                                                                                                    • this doesn't work if the chunk size is less than the input array size.

                                                                                                                                      – r3wt
                                                                                                                                      May 7 '18 at 19:30



















                                                                                                                                    • dont forget to make: newArr= a local variable

                                                                                                                                      – zgthompson
                                                                                                                                      Feb 25 '18 at 21:20











                                                                                                                                    • Code-only Answers tend to get flagged and then deleted for being Low Quality. Could you provide some commentary around how this solves the original problem?

                                                                                                                                      – Graham
                                                                                                                                      Feb 25 '18 at 21:57











                                                                                                                                    • this doesn't work if the chunk size is less than the input array size.

                                                                                                                                      – r3wt
                                                                                                                                      May 7 '18 at 19:30

















                                                                                                                                    dont forget to make: newArr= a local variable

                                                                                                                                    – zgthompson
                                                                                                                                    Feb 25 '18 at 21:20





                                                                                                                                    dont forget to make: newArr= a local variable

                                                                                                                                    – zgthompson
                                                                                                                                    Feb 25 '18 at 21:20













                                                                                                                                    Code-only Answers tend to get flagged and then deleted for being Low Quality. Could you provide some commentary around how this solves the original problem?

                                                                                                                                    – Graham
                                                                                                                                    Feb 25 '18 at 21:57





                                                                                                                                    Code-only Answers tend to get flagged and then deleted for being Low Quality. Could you provide some commentary around how this solves the original problem?

                                                                                                                                    – Graham
                                                                                                                                    Feb 25 '18 at 21:57













                                                                                                                                    this doesn't work if the chunk size is less than the input array size.

                                                                                                                                    – r3wt
                                                                                                                                    May 7 '18 at 19:30





                                                                                                                                    this doesn't work if the chunk size is less than the input array size.

                                                                                                                                    – r3wt
                                                                                                                                    May 7 '18 at 19:30











                                                                                                                                    0














                                                                                                                                    Array.reduce could be inefficient for large arrays, especially with the mod operator. I think a cleaner (and possibly easier to read) functional solution would be this:



                                                                                                                                    const chunkArray = (arr, size) =>
                                                                                                                                    arr.length > size
                                                                                                                                    ? [arr.slice(0, size), ...chunkArray(arr.slice(size), size)]
                                                                                                                                    : [arr];





                                                                                                                                    share|improve this answer




























                                                                                                                                      0














                                                                                                                                      Array.reduce could be inefficient for large arrays, especially with the mod operator. I think a cleaner (and possibly easier to read) functional solution would be this:



                                                                                                                                      const chunkArray = (arr, size) =>
                                                                                                                                      arr.length > size
                                                                                                                                      ? [arr.slice(0, size), ...chunkArray(arr.slice(size), size)]
                                                                                                                                      : [arr];





                                                                                                                                      share|improve this answer


























                                                                                                                                        0












                                                                                                                                        0








                                                                                                                                        0







                                                                                                                                        Array.reduce could be inefficient for large arrays, especially with the mod operator. I think a cleaner (and possibly easier to read) functional solution would be this:



                                                                                                                                        const chunkArray = (arr, size) =>
                                                                                                                                        arr.length > size
                                                                                                                                        ? [arr.slice(0, size), ...chunkArray(arr.slice(size), size)]
                                                                                                                                        : [arr];





                                                                                                                                        share|improve this answer













                                                                                                                                        Array.reduce could be inefficient for large arrays, especially with the mod operator. I think a cleaner (and possibly easier to read) functional solution would be this:



                                                                                                                                        const chunkArray = (arr, size) =>
                                                                                                                                        arr.length > size
                                                                                                                                        ? [arr.slice(0, size), ...chunkArray(arr.slice(size), size)]
                                                                                                                                        : [arr];






                                                                                                                                        share|improve this answer












                                                                                                                                        share|improve this answer



                                                                                                                                        share|improve this answer










                                                                                                                                        answered Jan 3 at 20:25









                                                                                                                                        tawnos178tawnos178

                                                                                                                                        411




                                                                                                                                        411






























                                                                                                                                            draft saved

                                                                                                                                            draft discarded




















































                                                                                                                                            Thanks for contributing an answer to Stack Overflow!


                                                                                                                                            • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                            But avoid



                                                                                                                                            • Asking for help, clarification, or responding to other answers.

                                                                                                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                            To learn more, see our tips on writing great answers.




                                                                                                                                            draft saved


                                                                                                                                            draft discarded














                                                                                                                                            StackExchange.ready(
                                                                                                                                            function () {
                                                                                                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7273668%2fhow-to-split-a-long-array-into-smaller-arrays-with-javascript%23new-answer', 'question_page');
                                                                                                                                            }
                                                                                                                                            );

                                                                                                                                            Post as a guest















                                                                                                                                            Required, but never shown





















































                                                                                                                                            Required, but never shown














                                                                                                                                            Required, but never shown












                                                                                                                                            Required, but never shown







                                                                                                                                            Required, but never shown

































                                                                                                                                            Required, but never shown














                                                                                                                                            Required, but never shown












                                                                                                                                            Required, but never shown







                                                                                                                                            Required, but never shown







                                                                                                                                            Popular posts from this blog

                                                                                                                                            Monofisismo

                                                                                                                                            Angular Downloading a file using contenturl with Basic Authentication

                                                                                                                                            Olmecas