Splitting a JS array into N arrays










58















Imagine I have an JS array like this:



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


What I want is to split that array into N smaller arrays. For instance:



split_list_in_n(a, 2)
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11]]

For N = 3:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

For N = 4:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

For N = 5:
[[1, 2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]


For Python, I have this:



def split_list_in_n(l, cols):
""" Split up a list in n lists evenly size chuncks """
start = 0
for i in xrange(cols):
stop = start + len(l[i::cols])
yield l[start:stop]
start = stop


For JS, the best right solution that I could come up with is a recursive function, but I don't like it because it's complicated and ugly. This inner function returns an array like this [1, 2, 3, null, 4, 5, 6, null, 7, 8], and then I have to loop it again and split it manually. (My first attempt was returning this: [1, 2, 3, [4, 5, 6, [7, 8, 9]]], and I decided to do it with the null separator).



function split(array, cols) 
if (cols==1) return array;
var size = Math.ceil(array.length / cols);
return array.slice(0, size).concat([null]).concat(split(array.slice(size), cols-1));



Here's a jsfiddle of that: http://jsfiddle.net/uduhH/



How would you do that? Thanks!










share|improve this question

















  • 2





    related to - stackoverflow.com/q/40166199/104380

    – vsync
    Oct 21 '16 at 8:11






  • 1





    Your split function is not far off. You can remove the null business by adding two array wrappers: if (cols == 1) return [array] and return [array.slice(0, size)].concat(split(array.slice(size), cols-1)). I find this recursive version much more readable than most of the answers here.

    – Scott Sauyet
    Oct 3 '18 at 18:41















58















Imagine I have an JS array like this:



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


What I want is to split that array into N smaller arrays. For instance:



split_list_in_n(a, 2)
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11]]

For N = 3:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

For N = 4:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

For N = 5:
[[1, 2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]


For Python, I have this:



def split_list_in_n(l, cols):
""" Split up a list in n lists evenly size chuncks """
start = 0
for i in xrange(cols):
stop = start + len(l[i::cols])
yield l[start:stop]
start = stop


For JS, the best right solution that I could come up with is a recursive function, but I don't like it because it's complicated and ugly. This inner function returns an array like this [1, 2, 3, null, 4, 5, 6, null, 7, 8], and then I have to loop it again and split it manually. (My first attempt was returning this: [1, 2, 3, [4, 5, 6, [7, 8, 9]]], and I decided to do it with the null separator).



function split(array, cols) 
if (cols==1) return array;
var size = Math.ceil(array.length / cols);
return array.slice(0, size).concat([null]).concat(split(array.slice(size), cols-1));



Here's a jsfiddle of that: http://jsfiddle.net/uduhH/



How would you do that? Thanks!










share|improve this question

















  • 2





    related to - stackoverflow.com/q/40166199/104380

    – vsync
    Oct 21 '16 at 8:11






  • 1





    Your split function is not far off. You can remove the null business by adding two array wrappers: if (cols == 1) return [array] and return [array.slice(0, size)].concat(split(array.slice(size), cols-1)). I find this recursive version much more readable than most of the answers here.

    – Scott Sauyet
    Oct 3 '18 at 18:41













58












58








58


27






Imagine I have an JS array like this:



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


What I want is to split that array into N smaller arrays. For instance:



split_list_in_n(a, 2)
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11]]

For N = 3:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

For N = 4:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

For N = 5:
[[1, 2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]


For Python, I have this:



def split_list_in_n(l, cols):
""" Split up a list in n lists evenly size chuncks """
start = 0
for i in xrange(cols):
stop = start + len(l[i::cols])
yield l[start:stop]
start = stop


For JS, the best right solution that I could come up with is a recursive function, but I don't like it because it's complicated and ugly. This inner function returns an array like this [1, 2, 3, null, 4, 5, 6, null, 7, 8], and then I have to loop it again and split it manually. (My first attempt was returning this: [1, 2, 3, [4, 5, 6, [7, 8, 9]]], and I decided to do it with the null separator).



function split(array, cols) 
if (cols==1) return array;
var size = Math.ceil(array.length / cols);
return array.slice(0, size).concat([null]).concat(split(array.slice(size), cols-1));



Here's a jsfiddle of that: http://jsfiddle.net/uduhH/



How would you do that? Thanks!










share|improve this question














Imagine I have an JS array like this:



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


What I want is to split that array into N smaller arrays. For instance:



split_list_in_n(a, 2)
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11]]

For N = 3:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

For N = 4:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]

For N = 5:
[[1, 2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]


For Python, I have this:



def split_list_in_n(l, cols):
""" Split up a list in n lists evenly size chuncks """
start = 0
for i in xrange(cols):
stop = start + len(l[i::cols])
yield l[start:stop]
start = stop


For JS, the best right solution that I could come up with is a recursive function, but I don't like it because it's complicated and ugly. This inner function returns an array like this [1, 2, 3, null, 4, 5, 6, null, 7, 8], and then I have to loop it again and split it manually. (My first attempt was returning this: [1, 2, 3, [4, 5, 6, [7, 8, 9]]], and I decided to do it with the null separator).



function split(array, cols) 
if (cols==1) return array;
var size = Math.ceil(array.length / cols);
return array.slice(0, size).concat([null]).concat(split(array.slice(size), cols-1));



Here's a jsfiddle of that: http://jsfiddle.net/uduhH/



How would you do that? Thanks!







javascript arrays






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 18 '11 at 20:14









TiagoTiago

6,63233432




6,63233432







  • 2





    related to - stackoverflow.com/q/40166199/104380

    – vsync
    Oct 21 '16 at 8:11






  • 1





    Your split function is not far off. You can remove the null business by adding two array wrappers: if (cols == 1) return [array] and return [array.slice(0, size)].concat(split(array.slice(size), cols-1)). I find this recursive version much more readable than most of the answers here.

    – Scott Sauyet
    Oct 3 '18 at 18:41












  • 2





    related to - stackoverflow.com/q/40166199/104380

    – vsync
    Oct 21 '16 at 8:11






  • 1





    Your split function is not far off. You can remove the null business by adding two array wrappers: if (cols == 1) return [array] and return [array.slice(0, size)].concat(split(array.slice(size), cols-1)). I find this recursive version much more readable than most of the answers here.

    – Scott Sauyet
    Oct 3 '18 at 18:41







2




2





related to - stackoverflow.com/q/40166199/104380

– vsync
Oct 21 '16 at 8:11





related to - stackoverflow.com/q/40166199/104380

– vsync
Oct 21 '16 at 8:11




1




1





Your split function is not far off. You can remove the null business by adding two array wrappers: if (cols == 1) return [array] and return [array.slice(0, size)].concat(split(array.slice(size), cols-1)). I find this recursive version much more readable than most of the answers here.

– Scott Sauyet
Oct 3 '18 at 18:41





Your split function is not far off. You can remove the null business by adding two array wrappers: if (cols == 1) return [array] and return [array.slice(0, size)].concat(split(array.slice(size), cols-1)). I find this recursive version much more readable than most of the answers here.

– Scott Sauyet
Oct 3 '18 at 18:41












18 Answers
18






active

oldest

votes


















115














You can make the slices "balanced" (subarrays' lengths differ as less as possible) or "even" (all subarrays but the last have the same length):






function chunkify(a, n, balanced) 

if (n < 2)
return [a];

var len = a.length,
out = ,
i = 0,
size;

if (len % n === 0)
size = Math.floor(len / n);
while (i < len)
out.push(a.slice(i, i += size));



else if (balanced)
while (i < len)
size = Math.ceil((len - i) / n--);
out.push(a.slice(i, i += size));



else

n--;
size = Math.floor(len / n);
if (len % size === 0)
size--;
while (i < size * n)
out.push(a.slice(i, i += size));

out.push(a.slice(size * n));



return out;



///////////////////////

onload = function ()
function $(x)
return document.getElementById(x);


function calc()
var s = +$('s').value, a = ;
while (s--)
a.unshift(s);
var n = +$('n').value;
$('b').textContent = JSON.stringify(chunkify(a, n, true))
$('e').textContent = JSON.stringify(chunkify(a, n, false))


$('s').addEventListener('input', calc);
$('n').addEventListener('input', calc);
calc();

<p>slice <input type="number" value="20" id="s"> items into
<input type="number" value="6" id="n"> chunks:</p>
<pre id="b"></pre>
<pre id="e"></pre>








share|improve this answer

























  • Your solution is neat, it does same thing that my recursive solution does but without all that mess. Thank you!

    – Tiago
    Nov 19 '11 at 12:32






  • 2





    Works like a charm.. Nice solution

    – Vardan
    Dec 3 '14 at 12:19











  • Hi @georg, can you please explain this line : var size = Math.ceil((len - i) / n--);

    – dpg5000
    Feb 11 '16 at 6:00












  • @dpg5000: when slicing the next chunk, its size is the number of remaining elements (len - i) by the number of remaining chunks (n--)

    – georg
    Feb 11 '16 at 6:28






  • 1





    @dpg5000: post updated

    – georg
    Feb 19 '16 at 9:11


















8














I just made an iterative implementation of the algorithm: http://jsfiddle.net/ht22q/. It passes your test cases.



function splitUp(arr, n) 
var rest = arr.length % n, // how much to divide
restUsed = rest, // to keep track of the division over the elements
partLength = Math.floor(arr.length / n),
result = ;

for(var i = 0; i < arr.length; i += partLength)
var end = partLength + i,
add = false;

if(rest !== 0 && restUsed) // should add one element for the division
end++;
restUsed--; // we've used one division element now
add = true;


result.push(arr.slice(i, end)); // part of the array

if(add)
i++; // also increment i in the case we added an extra element for division



return result;






share|improve this answer


















  • 1





    (This works as expected, but I can only choose one answer as correct) Hi! Thanks for helping. Nice thinking about how to use the rest.

    – Tiago
    Nov 19 '11 at 12:34



















5

















function split(arr, n) 
var res = ;
while (arr.length)
res.push(arr.splice(0, n));

return res;








share|improve this answer


















  • 1





    This does not works as expected for n = 5 and arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].

    – Tiago
    Sep 27 '14 at 16:51







  • 1





    this doesn't split to n subarrays, merely to subarrays of n length.

    – dpg5000
    Feb 17 '16 at 1:28






  • 1





    Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See How to Answer for more information.

    – Heretic Monkey
    Oct 21 '16 at 21:49


















5














I think this way using splice is the cleanest:



splitToChunks(array, parts) 
let result = ;
for (let i = parts; i > 0; i--)
result.push(array.splice(0, Math.ceil(array.length / i)));

return result;



For example, for parts = 3, you would take 1/3, then 1/2 of the remaining part, then the rest of the array. Math.ceil ensures that in case of uneven number of elements they will go to the earliest chunks.



(Note: this destroys the initial array.)






share|improve this answer
































    4














    You can reduce it into a matrix. The example below split the array (arr) into a matrix of two-positions arrays. If you want other sizes just change the 2 value on the second line:



    target.reduce((memo, value, index) => 
    if (index % 2 == 0 && index !== 0) memo.push()
    memo[memo.length - 1].push(value)
    return memo
    , [])


    Hope it helps!



    EDIT: Because some people is still commenting this doesn't answer the question since I was fixing the size of each chunk instead of the number of chunks I want. Here it comes the code explaining what I'm trying to explain in the comments section: Using the target.length.






    // Chunk function

    const chunk = (target, size) =>
    return target.reduce((memo, value, index) =>
    // Here it comes the only difference
    if (index % (target.length / size) == 0 && index !== 0) memo.push()
    memo[memo.length - 1].push(value)
    return memo
    , [])


    // Usage

    write(chunk([1, 2, 3, 4], 2))
    write(chunk([1, 2, 3, 4], 4))

    // For rendering pruposes. Ignore
    function write (content) document.write(JSON.stringify(content), '</br>')








    share|improve this answer




















    • 2





      Wow nice and concise way to do this! Love it! Great job! :-)

      – Philippe Monnet
      Aug 8 '15 at 22:05






    • 1





      I love this technique, but it's not answering the question. It returns any amount of x-sized chunks, whereas the questions was asking for x amount of evenly-sized chunks.

      – Jodi Warren
      Jan 21 '16 at 11:53






    • 3





      Love this !!! I've refactored to return evenly-sized chunks function splitArr(arr, n) return arr.reduce(function (a, i) if (a[a.length - 1].length >= arr.length / n) a.push() a[a.length - 1].push(i) return a; , [])

      – davide andreazzini
      Jul 29 '16 at 12:40












    • This doesn't answer the question at all, it's about fixed size of chunks, not fixed size of items-per-chunk

      – vsync
      Oct 20 '16 at 22:43






    • 2





      definitely does not answer the question.

      – macdelacruz
      Jun 14 '17 at 9:53


















    3














    Old question, but since vanillaJS is not a requirement and so many are trying to solve this with lodash/chunk, and without mistaking what _.chunk actually does, here's a concise + accurate solution using lodash:



    (Unlike the accepted answer, this also guarantees n columns even if originalArray.length < numCols)



    import _chunk from 'lodash/chunk'

    /**
    * Split an array into n subarrays (or columns)
    * @param Array flatArray Doesn't necessarily have to be flat, but this func only works 1 level deep
    * @param Number numCols The desired number of columns
    * @return Array
    */
    export function splitArray(flatArray, numCols)
    const maxColLength = Math.ceil(flatArray.length/numCols)
    const nestedArray = _chunk(flatArray, maxColLength)
    let newArray =
    for (var i = 0; i < numCols; i++)
    newArray[i] = nestedArray[i]
    return newArray



    The for loop at the end is what guarantees the desired number of "columns".






    share|improve this answer
































      2














      Recursive approach, not tested.



      function splitArray(array, parts, out) 
      var
      len = array.length
      , partLen

      if (parts < len)
      partLen = Math.ceil(len / parts);
      out.push(array.slice(0, partLen));
      if (parts > 1)
      splitArray(array.slice(partLen), parts - 1, out);

      else
      out.push(array);







      share|improve this answer






























        2














        Another recursive works quite well, it is less ugly



        function nSmaller(num, arr, sliced) ;
        if(num === 0)
        return sliced;


        var len = arr.length,
        point = Math.ceil(len/num),
        nextArr = arr.slice(point);

        mySliced.push(arr.slice(0, point));
        nSmaller(num-1, nextArr, mySliced);

        return(mySliced);






        share|improve this answer






























          1














          Probably the cleaner approach would be the following (without using any other library) :



          var myArray = ;
          for(var i=0; i<100; i++)
          myArray.push(i+1);

          console.log(myArray);

          function chunk(arr, size)
          var chunkedArr = ;
          var noOfChunks = Math.ceil(arr.length/size);
          console.log(noOfChunks);
          for(var i=0; i<noOfChunks; i++)
          chunkedArr.push(arr.slice(i*size, (i+1)*size));

          return chunkedArr;


          var chunkedArr = chunk(myArray, 3);
          console.log(chunkedArr);


          I have created my own array which is to be chunked. You can find the code here



          Also we have a method "chunk" in the lodash library which is of great use. Hope that helps






          share|improve this answer






























            1














            function splitArray(arr, numOfParts = 10)
            const splitedArray =
            for (let i = 0; i < numOfParts;i++)
            const numOfItemsToSplice = arr.length / 10;
            splitedArray.push(arr.splice(0, numOfItemsToSplice))

            return splitedArray;






            share|improve this answer






























              0














              I made it this way, it works...



              function splitArray(array, parts) 
              if (parts< array.length && array.length > 1 && array != null)
              var newArray = ;
              var counter1 = 0;
              var counter2 = 0;

              while (counter1 < parts)
              newArray.push();
              counter1 += 1;


              for (var i = 0; i < array.length; i++)
              newArray[counter2++].push(array[i]);
              if (counter2 > parts - 1)
              counter2 = 0;


              return newArray;
              else
              return array;






              share|improve this answer






























                0














                check my version of this array split



                // divide array
                Array.prototype.divideIt = function(d)
                if(this.length <= d) return this;
                var arr = this,
                hold = ,
                ref = -1;
                for(var i = 0; i < arr.length; i++)
                if(i % d === 0)
                ref++;

                if(typeof hold[ref] === 'undefined')
                hold[ref] = ;

                hold[ref].push(arr[i]);


                return hold;
                ;





                share|improve this answer






























                  0














                  if you know wanna set child_arrays.length then i think this solution best:



                  function sp(size, arr) //size - child_array.length
                  var out = ,i = 0, n= Math.ceil((arr.length)/size);
                  while(i < n) out.push(arr.splice(0, (i==n-1) && size < arr.length ? arr.length: size)); i++;
                  return out;



                  call fn:
                  sp(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) //2 - child_arrat.length



                  answer:
                  [1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]






                  share|improve this answer






























                    0














                    Just use lodash' chunk function to split the array into smaller arrays https://lodash.com/docs#chunk No need to fiddle with the loops anymore!






                    share|improve this answer


















                    • 1





                      The question asks how to solve this using vannila js, not using js libraries

                      – T J
                      Dec 15 '15 at 16:34






                    • 2





                      Thanks for bringing this up. I didn't know lodash had this.

                      – Tiago
                      Jan 22 '16 at 11:03






                    • 9





                      This also doesn't answer the question. He wants N arrays, not arrays of N elements.

                      – mAAdhaTTah
                      Feb 9 '16 at 14:53


















                    0














                    If you can use lodash and would like a functional programming approach, here is what I come up with:



                    const _ = require('lodash')

                    function splitArray(array, numChunks)
                    return _.reduce(_.range(numChunks), (array, result, numChunks, chunkIndex) =>
                    const numItems = Math.ceil(array.length / numChunks)
                    const items = _.take(array, numItems)
                    result.push(items)
                    return
                    array: _.drop(array, numItems),
                    result,
                    numChunks: numChunks - 1

                    ,
                    array,
                    result: ,
                    numChunks
                    ).result






                    share|improve this answer
































                      0














                      all above might work fine, but what if you have associative array with strings as keys?



                      objectKeys = Object.keys;

                      arraySplit(arr, n)
                      let counter = 0;
                      for (const a of this.objectKeys(arr))
                      this.arr[(counter%n)][a] = arr[a];
                      counter++;







                      share|improve this answer






























                        -1














                        function parseToPages(elements, pageSize = 8) 
                        var result = ;
                        while (elements.length)
                        result.push(elements.splice(0, pageSize));

                        return result;






                        share|improve this answer


















                        • 1





                          Please don't just dump code as an answer. Add an explanation how this addresses the problem of the question.

                          – Mark Rotteveel
                          Dec 10 '18 at 18:28


















                        -3














                        If you are using lodash, you can achieve it fairly easily like below:



                        import chunk from 'lodash';
                        // divides the array into 2 sections
                        chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 2); // => [[1,2,3,4,5,6], [7,8,9,10,11]]





                        share|improve this answer


















                        • 3





                          This is wrong. _.chunk creates arrays of N elements not N arrays. Your example would have an output of 6 arrays with 2 elements in each exept the last one [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]]

                          – Vassilis Barzokas
                          Dec 23 '16 at 11:00











                        • thats what the original question is. please read the expected behaviour in the question.

                          – abhisekpaul
                          Mar 14 '17 at 13:38











                        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%2f8188548%2fsplitting-a-js-array-into-n-arrays%23new-answer', 'question_page');

                        );

                        Post as a guest















                        Required, but never shown

























                        18 Answers
                        18






                        active

                        oldest

                        votes








                        18 Answers
                        18






                        active

                        oldest

                        votes









                        active

                        oldest

                        votes






                        active

                        oldest

                        votes









                        115














                        You can make the slices "balanced" (subarrays' lengths differ as less as possible) or "even" (all subarrays but the last have the same length):






                        function chunkify(a, n, balanced) 

                        if (n < 2)
                        return [a];

                        var len = a.length,
                        out = ,
                        i = 0,
                        size;

                        if (len % n === 0)
                        size = Math.floor(len / n);
                        while (i < len)
                        out.push(a.slice(i, i += size));



                        else if (balanced)
                        while (i < len)
                        size = Math.ceil((len - i) / n--);
                        out.push(a.slice(i, i += size));



                        else

                        n--;
                        size = Math.floor(len / n);
                        if (len % size === 0)
                        size--;
                        while (i < size * n)
                        out.push(a.slice(i, i += size));

                        out.push(a.slice(size * n));



                        return out;



                        ///////////////////////

                        onload = function ()
                        function $(x)
                        return document.getElementById(x);


                        function calc()
                        var s = +$('s').value, a = ;
                        while (s--)
                        a.unshift(s);
                        var n = +$('n').value;
                        $('b').textContent = JSON.stringify(chunkify(a, n, true))
                        $('e').textContent = JSON.stringify(chunkify(a, n, false))


                        $('s').addEventListener('input', calc);
                        $('n').addEventListener('input', calc);
                        calc();

                        <p>slice <input type="number" value="20" id="s"> items into
                        <input type="number" value="6" id="n"> chunks:</p>
                        <pre id="b"></pre>
                        <pre id="e"></pre>








                        share|improve this answer

























                        • Your solution is neat, it does same thing that my recursive solution does but without all that mess. Thank you!

                          – Tiago
                          Nov 19 '11 at 12:32






                        • 2





                          Works like a charm.. Nice solution

                          – Vardan
                          Dec 3 '14 at 12:19











                        • Hi @georg, can you please explain this line : var size = Math.ceil((len - i) / n--);

                          – dpg5000
                          Feb 11 '16 at 6:00












                        • @dpg5000: when slicing the next chunk, its size is the number of remaining elements (len - i) by the number of remaining chunks (n--)

                          – georg
                          Feb 11 '16 at 6:28






                        • 1





                          @dpg5000: post updated

                          – georg
                          Feb 19 '16 at 9:11















                        115














                        You can make the slices "balanced" (subarrays' lengths differ as less as possible) or "even" (all subarrays but the last have the same length):






                        function chunkify(a, n, balanced) 

                        if (n < 2)
                        return [a];

                        var len = a.length,
                        out = ,
                        i = 0,
                        size;

                        if (len % n === 0)
                        size = Math.floor(len / n);
                        while (i < len)
                        out.push(a.slice(i, i += size));



                        else if (balanced)
                        while (i < len)
                        size = Math.ceil((len - i) / n--);
                        out.push(a.slice(i, i += size));



                        else

                        n--;
                        size = Math.floor(len / n);
                        if (len % size === 0)
                        size--;
                        while (i < size * n)
                        out.push(a.slice(i, i += size));

                        out.push(a.slice(size * n));



                        return out;



                        ///////////////////////

                        onload = function ()
                        function $(x)
                        return document.getElementById(x);


                        function calc()
                        var s = +$('s').value, a = ;
                        while (s--)
                        a.unshift(s);
                        var n = +$('n').value;
                        $('b').textContent = JSON.stringify(chunkify(a, n, true))
                        $('e').textContent = JSON.stringify(chunkify(a, n, false))


                        $('s').addEventListener('input', calc);
                        $('n').addEventListener('input', calc);
                        calc();

                        <p>slice <input type="number" value="20" id="s"> items into
                        <input type="number" value="6" id="n"> chunks:</p>
                        <pre id="b"></pre>
                        <pre id="e"></pre>








                        share|improve this answer

























                        • Your solution is neat, it does same thing that my recursive solution does but without all that mess. Thank you!

                          – Tiago
                          Nov 19 '11 at 12:32






                        • 2





                          Works like a charm.. Nice solution

                          – Vardan
                          Dec 3 '14 at 12:19











                        • Hi @georg, can you please explain this line : var size = Math.ceil((len - i) / n--);

                          – dpg5000
                          Feb 11 '16 at 6:00












                        • @dpg5000: when slicing the next chunk, its size is the number of remaining elements (len - i) by the number of remaining chunks (n--)

                          – georg
                          Feb 11 '16 at 6:28






                        • 1





                          @dpg5000: post updated

                          – georg
                          Feb 19 '16 at 9:11













                        115












                        115








                        115







                        You can make the slices "balanced" (subarrays' lengths differ as less as possible) or "even" (all subarrays but the last have the same length):






                        function chunkify(a, n, balanced) 

                        if (n < 2)
                        return [a];

                        var len = a.length,
                        out = ,
                        i = 0,
                        size;

                        if (len % n === 0)
                        size = Math.floor(len / n);
                        while (i < len)
                        out.push(a.slice(i, i += size));



                        else if (balanced)
                        while (i < len)
                        size = Math.ceil((len - i) / n--);
                        out.push(a.slice(i, i += size));



                        else

                        n--;
                        size = Math.floor(len / n);
                        if (len % size === 0)
                        size--;
                        while (i < size * n)
                        out.push(a.slice(i, i += size));

                        out.push(a.slice(size * n));



                        return out;



                        ///////////////////////

                        onload = function ()
                        function $(x)
                        return document.getElementById(x);


                        function calc()
                        var s = +$('s').value, a = ;
                        while (s--)
                        a.unshift(s);
                        var n = +$('n').value;
                        $('b').textContent = JSON.stringify(chunkify(a, n, true))
                        $('e').textContent = JSON.stringify(chunkify(a, n, false))


                        $('s').addEventListener('input', calc);
                        $('n').addEventListener('input', calc);
                        calc();

                        <p>slice <input type="number" value="20" id="s"> items into
                        <input type="number" value="6" id="n"> chunks:</p>
                        <pre id="b"></pre>
                        <pre id="e"></pre>








                        share|improve this answer















                        You can make the slices "balanced" (subarrays' lengths differ as less as possible) or "even" (all subarrays but the last have the same length):






                        function chunkify(a, n, balanced) 

                        if (n < 2)
                        return [a];

                        var len = a.length,
                        out = ,
                        i = 0,
                        size;

                        if (len % n === 0)
                        size = Math.floor(len / n);
                        while (i < len)
                        out.push(a.slice(i, i += size));



                        else if (balanced)
                        while (i < len)
                        size = Math.ceil((len - i) / n--);
                        out.push(a.slice(i, i += size));



                        else

                        n--;
                        size = Math.floor(len / n);
                        if (len % size === 0)
                        size--;
                        while (i < size * n)
                        out.push(a.slice(i, i += size));

                        out.push(a.slice(size * n));



                        return out;



                        ///////////////////////

                        onload = function ()
                        function $(x)
                        return document.getElementById(x);


                        function calc()
                        var s = +$('s').value, a = ;
                        while (s--)
                        a.unshift(s);
                        var n = +$('n').value;
                        $('b').textContent = JSON.stringify(chunkify(a, n, true))
                        $('e').textContent = JSON.stringify(chunkify(a, n, false))


                        $('s').addEventListener('input', calc);
                        $('n').addEventListener('input', calc);
                        calc();

                        <p>slice <input type="number" value="20" id="s"> items into
                        <input type="number" value="6" id="n"> chunks:</p>
                        <pre id="b"></pre>
                        <pre id="e"></pre>








                        function chunkify(a, n, balanced) 

                        if (n < 2)
                        return [a];

                        var len = a.length,
                        out = ,
                        i = 0,
                        size;

                        if (len % n === 0)
                        size = Math.floor(len / n);
                        while (i < len)
                        out.push(a.slice(i, i += size));



                        else if (balanced)
                        while (i < len)
                        size = Math.ceil((len - i) / n--);
                        out.push(a.slice(i, i += size));



                        else

                        n--;
                        size = Math.floor(len / n);
                        if (len % size === 0)
                        size--;
                        while (i < size * n)
                        out.push(a.slice(i, i += size));

                        out.push(a.slice(size * n));



                        return out;



                        ///////////////////////

                        onload = function ()
                        function $(x)
                        return document.getElementById(x);


                        function calc()
                        var s = +$('s').value, a = ;
                        while (s--)
                        a.unshift(s);
                        var n = +$('n').value;
                        $('b').textContent = JSON.stringify(chunkify(a, n, true))
                        $('e').textContent = JSON.stringify(chunkify(a, n, false))


                        $('s').addEventListener('input', calc);
                        $('n').addEventListener('input', calc);
                        calc();

                        <p>slice <input type="number" value="20" id="s"> items into
                        <input type="number" value="6" id="n"> chunks:</p>
                        <pre id="b"></pre>
                        <pre id="e"></pre>





                        function chunkify(a, n, balanced) 

                        if (n < 2)
                        return [a];

                        var len = a.length,
                        out = ,
                        i = 0,
                        size;

                        if (len % n === 0)
                        size = Math.floor(len / n);
                        while (i < len)
                        out.push(a.slice(i, i += size));



                        else if (balanced)
                        while (i < len)
                        size = Math.ceil((len - i) / n--);
                        out.push(a.slice(i, i += size));



                        else

                        n--;
                        size = Math.floor(len / n);
                        if (len % size === 0)
                        size--;
                        while (i < size * n)
                        out.push(a.slice(i, i += size));

                        out.push(a.slice(size * n));



                        return out;



                        ///////////////////////

                        onload = function ()
                        function $(x)
                        return document.getElementById(x);


                        function calc()
                        var s = +$('s').value, a = ;
                        while (s--)
                        a.unshift(s);
                        var n = +$('n').value;
                        $('b').textContent = JSON.stringify(chunkify(a, n, true))
                        $('e').textContent = JSON.stringify(chunkify(a, n, false))


                        $('s').addEventListener('input', calc);
                        $('n').addEventListener('input', calc);
                        calc();

                        <p>slice <input type="number" value="20" id="s"> items into
                        <input type="number" value="6" id="n"> chunks:</p>
                        <pre id="b"></pre>
                        <pre id="e"></pre>






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Apr 13 '16 at 5:29









                        mgilson

                        211k39412528




                        211k39412528










                        answered Nov 18 '11 at 21:16









                        georggeorg

                        150k35204300




                        150k35204300












                        • Your solution is neat, it does same thing that my recursive solution does but without all that mess. Thank you!

                          – Tiago
                          Nov 19 '11 at 12:32






                        • 2





                          Works like a charm.. Nice solution

                          – Vardan
                          Dec 3 '14 at 12:19











                        • Hi @georg, can you please explain this line : var size = Math.ceil((len - i) / n--);

                          – dpg5000
                          Feb 11 '16 at 6:00












                        • @dpg5000: when slicing the next chunk, its size is the number of remaining elements (len - i) by the number of remaining chunks (n--)

                          – georg
                          Feb 11 '16 at 6:28






                        • 1





                          @dpg5000: post updated

                          – georg
                          Feb 19 '16 at 9:11

















                        • Your solution is neat, it does same thing that my recursive solution does but without all that mess. Thank you!

                          – Tiago
                          Nov 19 '11 at 12:32






                        • 2





                          Works like a charm.. Nice solution

                          – Vardan
                          Dec 3 '14 at 12:19











                        • Hi @georg, can you please explain this line : var size = Math.ceil((len - i) / n--);

                          – dpg5000
                          Feb 11 '16 at 6:00












                        • @dpg5000: when slicing the next chunk, its size is the number of remaining elements (len - i) by the number of remaining chunks (n--)

                          – georg
                          Feb 11 '16 at 6:28






                        • 1





                          @dpg5000: post updated

                          – georg
                          Feb 19 '16 at 9:11
















                        Your solution is neat, it does same thing that my recursive solution does but without all that mess. Thank you!

                        – Tiago
                        Nov 19 '11 at 12:32





                        Your solution is neat, it does same thing that my recursive solution does but without all that mess. Thank you!

                        – Tiago
                        Nov 19 '11 at 12:32




                        2




                        2





                        Works like a charm.. Nice solution

                        – Vardan
                        Dec 3 '14 at 12:19





                        Works like a charm.. Nice solution

                        – Vardan
                        Dec 3 '14 at 12:19













                        Hi @georg, can you please explain this line : var size = Math.ceil((len - i) / n--);

                        – dpg5000
                        Feb 11 '16 at 6:00






                        Hi @georg, can you please explain this line : var size = Math.ceil((len - i) / n--);

                        – dpg5000
                        Feb 11 '16 at 6:00














                        @dpg5000: when slicing the next chunk, its size is the number of remaining elements (len - i) by the number of remaining chunks (n--)

                        – georg
                        Feb 11 '16 at 6:28





                        @dpg5000: when slicing the next chunk, its size is the number of remaining elements (len - i) by the number of remaining chunks (n--)

                        – georg
                        Feb 11 '16 at 6:28




                        1




                        1





                        @dpg5000: post updated

                        – georg
                        Feb 19 '16 at 9:11





                        @dpg5000: post updated

                        – georg
                        Feb 19 '16 at 9:11













                        8














                        I just made an iterative implementation of the algorithm: http://jsfiddle.net/ht22q/. It passes your test cases.



                        function splitUp(arr, n) 
                        var rest = arr.length % n, // how much to divide
                        restUsed = rest, // to keep track of the division over the elements
                        partLength = Math.floor(arr.length / n),
                        result = ;

                        for(var i = 0; i < arr.length; i += partLength)
                        var end = partLength + i,
                        add = false;

                        if(rest !== 0 && restUsed) // should add one element for the division
                        end++;
                        restUsed--; // we've used one division element now
                        add = true;


                        result.push(arr.slice(i, end)); // part of the array

                        if(add)
                        i++; // also increment i in the case we added an extra element for division



                        return result;






                        share|improve this answer


















                        • 1





                          (This works as expected, but I can only choose one answer as correct) Hi! Thanks for helping. Nice thinking about how to use the rest.

                          – Tiago
                          Nov 19 '11 at 12:34
















                        8














                        I just made an iterative implementation of the algorithm: http://jsfiddle.net/ht22q/. It passes your test cases.



                        function splitUp(arr, n) 
                        var rest = arr.length % n, // how much to divide
                        restUsed = rest, // to keep track of the division over the elements
                        partLength = Math.floor(arr.length / n),
                        result = ;

                        for(var i = 0; i < arr.length; i += partLength)
                        var end = partLength + i,
                        add = false;

                        if(rest !== 0 && restUsed) // should add one element for the division
                        end++;
                        restUsed--; // we've used one division element now
                        add = true;


                        result.push(arr.slice(i, end)); // part of the array

                        if(add)
                        i++; // also increment i in the case we added an extra element for division



                        return result;






                        share|improve this answer


















                        • 1





                          (This works as expected, but I can only choose one answer as correct) Hi! Thanks for helping. Nice thinking about how to use the rest.

                          – Tiago
                          Nov 19 '11 at 12:34














                        8












                        8








                        8







                        I just made an iterative implementation of the algorithm: http://jsfiddle.net/ht22q/. It passes your test cases.



                        function splitUp(arr, n) 
                        var rest = arr.length % n, // how much to divide
                        restUsed = rest, // to keep track of the division over the elements
                        partLength = Math.floor(arr.length / n),
                        result = ;

                        for(var i = 0; i < arr.length; i += partLength)
                        var end = partLength + i,
                        add = false;

                        if(rest !== 0 && restUsed) // should add one element for the division
                        end++;
                        restUsed--; // we've used one division element now
                        add = true;


                        result.push(arr.slice(i, end)); // part of the array

                        if(add)
                        i++; // also increment i in the case we added an extra element for division



                        return result;






                        share|improve this answer













                        I just made an iterative implementation of the algorithm: http://jsfiddle.net/ht22q/. It passes your test cases.



                        function splitUp(arr, n) 
                        var rest = arr.length % n, // how much to divide
                        restUsed = rest, // to keep track of the division over the elements
                        partLength = Math.floor(arr.length / n),
                        result = ;

                        for(var i = 0; i < arr.length; i += partLength)
                        var end = partLength + i,
                        add = false;

                        if(rest !== 0 && restUsed) // should add one element for the division
                        end++;
                        restUsed--; // we've used one division element now
                        add = true;


                        result.push(arr.slice(i, end)); // part of the array

                        if(add)
                        i++; // also increment i in the case we added an extra element for division



                        return result;







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 18 '11 at 20:26









                        pimvdbpimvdb

                        113k57273336




                        113k57273336







                        • 1





                          (This works as expected, but I can only choose one answer as correct) Hi! Thanks for helping. Nice thinking about how to use the rest.

                          – Tiago
                          Nov 19 '11 at 12:34













                        • 1





                          (This works as expected, but I can only choose one answer as correct) Hi! Thanks for helping. Nice thinking about how to use the rest.

                          – Tiago
                          Nov 19 '11 at 12:34








                        1




                        1





                        (This works as expected, but I can only choose one answer as correct) Hi! Thanks for helping. Nice thinking about how to use the rest.

                        – Tiago
                        Nov 19 '11 at 12:34






                        (This works as expected, but I can only choose one answer as correct) Hi! Thanks for helping. Nice thinking about how to use the rest.

                        – Tiago
                        Nov 19 '11 at 12:34












                        5

















                        function split(arr, n) 
                        var res = ;
                        while (arr.length)
                        res.push(arr.splice(0, n));

                        return res;








                        share|improve this answer


















                        • 1





                          This does not works as expected for n = 5 and arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].

                          – Tiago
                          Sep 27 '14 at 16:51







                        • 1





                          this doesn't split to n subarrays, merely to subarrays of n length.

                          – dpg5000
                          Feb 17 '16 at 1:28






                        • 1





                          Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See How to Answer for more information.

                          – Heretic Monkey
                          Oct 21 '16 at 21:49















                        5

















                        function split(arr, n) 
                        var res = ;
                        while (arr.length)
                        res.push(arr.splice(0, n));

                        return res;








                        share|improve this answer


















                        • 1





                          This does not works as expected for n = 5 and arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].

                          – Tiago
                          Sep 27 '14 at 16:51







                        • 1





                          this doesn't split to n subarrays, merely to subarrays of n length.

                          – dpg5000
                          Feb 17 '16 at 1:28






                        • 1





                          Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See How to Answer for more information.

                          – Heretic Monkey
                          Oct 21 '16 at 21:49













                        5












                        5








                        5










                        function split(arr, n) 
                        var res = ;
                        while (arr.length)
                        res.push(arr.splice(0, n));

                        return res;








                        share|improve this answer
















                        function split(arr, n) 
                        var res = ;
                        while (arr.length)
                        res.push(arr.splice(0, n));

                        return res;








                        function split(arr, n) 
                        var res = ;
                        while (arr.length)
                        res.push(arr.splice(0, n));

                        return res;





                        function split(arr, n) 
                        var res = ;
                        while (arr.length)
                        res.push(arr.splice(0, n));

                        return res;






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Sep 27 '14 at 11:31









                        bagbeebagbee

                        7512




                        7512







                        • 1





                          This does not works as expected for n = 5 and arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].

                          – Tiago
                          Sep 27 '14 at 16:51







                        • 1





                          this doesn't split to n subarrays, merely to subarrays of n length.

                          – dpg5000
                          Feb 17 '16 at 1:28






                        • 1





                          Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See How to Answer for more information.

                          – Heretic Monkey
                          Oct 21 '16 at 21:49












                        • 1





                          This does not works as expected for n = 5 and arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].

                          – Tiago
                          Sep 27 '14 at 16:51







                        • 1





                          this doesn't split to n subarrays, merely to subarrays of n length.

                          – dpg5000
                          Feb 17 '16 at 1:28






                        • 1





                          Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See How to Answer for more information.

                          – Heretic Monkey
                          Oct 21 '16 at 21:49







                        1




                        1





                        This does not works as expected for n = 5 and arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].

                        – Tiago
                        Sep 27 '14 at 16:51






                        This does not works as expected for n = 5 and arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].

                        – Tiago
                        Sep 27 '14 at 16:51





                        1




                        1





                        this doesn't split to n subarrays, merely to subarrays of n length.

                        – dpg5000
                        Feb 17 '16 at 1:28





                        this doesn't split to n subarrays, merely to subarrays of n length.

                        – dpg5000
                        Feb 17 '16 at 1:28




                        1




                        1





                        Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See How to Answer for more information.

                        – Heretic Monkey
                        Oct 21 '16 at 21:49





                        Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See How to Answer for more information.

                        – Heretic Monkey
                        Oct 21 '16 at 21:49











                        5














                        I think this way using splice is the cleanest:



                        splitToChunks(array, parts) 
                        let result = ;
                        for (let i = parts; i > 0; i--)
                        result.push(array.splice(0, Math.ceil(array.length / i)));

                        return result;



                        For example, for parts = 3, you would take 1/3, then 1/2 of the remaining part, then the rest of the array. Math.ceil ensures that in case of uneven number of elements they will go to the earliest chunks.



                        (Note: this destroys the initial array.)






                        share|improve this answer





























                          5














                          I think this way using splice is the cleanest:



                          splitToChunks(array, parts) 
                          let result = ;
                          for (let i = parts; i > 0; i--)
                          result.push(array.splice(0, Math.ceil(array.length / i)));

                          return result;



                          For example, for parts = 3, you would take 1/3, then 1/2 of the remaining part, then the rest of the array. Math.ceil ensures that in case of uneven number of elements they will go to the earliest chunks.



                          (Note: this destroys the initial array.)






                          share|improve this answer



























                            5












                            5








                            5







                            I think this way using splice is the cleanest:



                            splitToChunks(array, parts) 
                            let result = ;
                            for (let i = parts; i > 0; i--)
                            result.push(array.splice(0, Math.ceil(array.length / i)));

                            return result;



                            For example, for parts = 3, you would take 1/3, then 1/2 of the remaining part, then the rest of the array. Math.ceil ensures that in case of uneven number of elements they will go to the earliest chunks.



                            (Note: this destroys the initial array.)






                            share|improve this answer















                            I think this way using splice is the cleanest:



                            splitToChunks(array, parts) 
                            let result = ;
                            for (let i = parts; i > 0; i--)
                            result.push(array.splice(0, Math.ceil(array.length / i)));

                            return result;



                            For example, for parts = 3, you would take 1/3, then 1/2 of the remaining part, then the rest of the array. Math.ceil ensures that in case of uneven number of elements they will go to the earliest chunks.



                            (Note: this destroys the initial array.)







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 14 '18 at 20:15

























                            answered Jul 25 '18 at 8:56









                            SentheSenthe

                            1,176822




                            1,176822





















                                4














                                You can reduce it into a matrix. The example below split the array (arr) into a matrix of two-positions arrays. If you want other sizes just change the 2 value on the second line:



                                target.reduce((memo, value, index) => 
                                if (index % 2 == 0 && index !== 0) memo.push()
                                memo[memo.length - 1].push(value)
                                return memo
                                , [])


                                Hope it helps!



                                EDIT: Because some people is still commenting this doesn't answer the question since I was fixing the size of each chunk instead of the number of chunks I want. Here it comes the code explaining what I'm trying to explain in the comments section: Using the target.length.






                                // Chunk function

                                const chunk = (target, size) =>
                                return target.reduce((memo, value, index) =>
                                // Here it comes the only difference
                                if (index % (target.length / size) == 0 && index !== 0) memo.push()
                                memo[memo.length - 1].push(value)
                                return memo
                                , [])


                                // Usage

                                write(chunk([1, 2, 3, 4], 2))
                                write(chunk([1, 2, 3, 4], 4))

                                // For rendering pruposes. Ignore
                                function write (content) document.write(JSON.stringify(content), '</br>')








                                share|improve this answer




















                                • 2





                                  Wow nice and concise way to do this! Love it! Great job! :-)

                                  – Philippe Monnet
                                  Aug 8 '15 at 22:05






                                • 1





                                  I love this technique, but it's not answering the question. It returns any amount of x-sized chunks, whereas the questions was asking for x amount of evenly-sized chunks.

                                  – Jodi Warren
                                  Jan 21 '16 at 11:53






                                • 3





                                  Love this !!! I've refactored to return evenly-sized chunks function splitArr(arr, n) return arr.reduce(function (a, i) if (a[a.length - 1].length >= arr.length / n) a.push() a[a.length - 1].push(i) return a; , [])

                                  – davide andreazzini
                                  Jul 29 '16 at 12:40












                                • This doesn't answer the question at all, it's about fixed size of chunks, not fixed size of items-per-chunk

                                  – vsync
                                  Oct 20 '16 at 22:43






                                • 2





                                  definitely does not answer the question.

                                  – macdelacruz
                                  Jun 14 '17 at 9:53















                                4














                                You can reduce it into a matrix. The example below split the array (arr) into a matrix of two-positions arrays. If you want other sizes just change the 2 value on the second line:



                                target.reduce((memo, value, index) => 
                                if (index % 2 == 0 && index !== 0) memo.push()
                                memo[memo.length - 1].push(value)
                                return memo
                                , [])


                                Hope it helps!



                                EDIT: Because some people is still commenting this doesn't answer the question since I was fixing the size of each chunk instead of the number of chunks I want. Here it comes the code explaining what I'm trying to explain in the comments section: Using the target.length.






                                // Chunk function

                                const chunk = (target, size) =>
                                return target.reduce((memo, value, index) =>
                                // Here it comes the only difference
                                if (index % (target.length / size) == 0 && index !== 0) memo.push()
                                memo[memo.length - 1].push(value)
                                return memo
                                , [])


                                // Usage

                                write(chunk([1, 2, 3, 4], 2))
                                write(chunk([1, 2, 3, 4], 4))

                                // For rendering pruposes. Ignore
                                function write (content) document.write(JSON.stringify(content), '</br>')








                                share|improve this answer




















                                • 2





                                  Wow nice and concise way to do this! Love it! Great job! :-)

                                  – Philippe Monnet
                                  Aug 8 '15 at 22:05






                                • 1





                                  I love this technique, but it's not answering the question. It returns any amount of x-sized chunks, whereas the questions was asking for x amount of evenly-sized chunks.

                                  – Jodi Warren
                                  Jan 21 '16 at 11:53






                                • 3





                                  Love this !!! I've refactored to return evenly-sized chunks function splitArr(arr, n) return arr.reduce(function (a, i) if (a[a.length - 1].length >= arr.length / n) a.push() a[a.length - 1].push(i) return a; , [])

                                  – davide andreazzini
                                  Jul 29 '16 at 12:40












                                • This doesn't answer the question at all, it's about fixed size of chunks, not fixed size of items-per-chunk

                                  – vsync
                                  Oct 20 '16 at 22:43






                                • 2





                                  definitely does not answer the question.

                                  – macdelacruz
                                  Jun 14 '17 at 9:53













                                4












                                4








                                4







                                You can reduce it into a matrix. The example below split the array (arr) into a matrix of two-positions arrays. If you want other sizes just change the 2 value on the second line:



                                target.reduce((memo, value, index) => 
                                if (index % 2 == 0 && index !== 0) memo.push()
                                memo[memo.length - 1].push(value)
                                return memo
                                , [])


                                Hope it helps!



                                EDIT: Because some people is still commenting this doesn't answer the question since I was fixing the size of each chunk instead of the number of chunks I want. Here it comes the code explaining what I'm trying to explain in the comments section: Using the target.length.






                                // Chunk function

                                const chunk = (target, size) =>
                                return target.reduce((memo, value, index) =>
                                // Here it comes the only difference
                                if (index % (target.length / size) == 0 && index !== 0) memo.push()
                                memo[memo.length - 1].push(value)
                                return memo
                                , [])


                                // Usage

                                write(chunk([1, 2, 3, 4], 2))
                                write(chunk([1, 2, 3, 4], 4))

                                // For rendering pruposes. Ignore
                                function write (content) document.write(JSON.stringify(content), '</br>')








                                share|improve this answer















                                You can reduce it into a matrix. The example below split the array (arr) into a matrix of two-positions arrays. If you want other sizes just change the 2 value on the second line:



                                target.reduce((memo, value, index) => 
                                if (index % 2 == 0 && index !== 0) memo.push()
                                memo[memo.length - 1].push(value)
                                return memo
                                , [])


                                Hope it helps!



                                EDIT: Because some people is still commenting this doesn't answer the question since I was fixing the size of each chunk instead of the number of chunks I want. Here it comes the code explaining what I'm trying to explain in the comments section: Using the target.length.






                                // Chunk function

                                const chunk = (target, size) =>
                                return target.reduce((memo, value, index) =>
                                // Here it comes the only difference
                                if (index % (target.length / size) == 0 && index !== 0) memo.push()
                                memo[memo.length - 1].push(value)
                                return memo
                                , [])


                                // Usage

                                write(chunk([1, 2, 3, 4], 2))
                                write(chunk([1, 2, 3, 4], 4))

                                // For rendering pruposes. Ignore
                                function write (content) document.write(JSON.stringify(content), '</br>')








                                // Chunk function

                                const chunk = (target, size) =>
                                return target.reduce((memo, value, index) =>
                                // Here it comes the only difference
                                if (index % (target.length / size) == 0 && index !== 0) memo.push()
                                memo[memo.length - 1].push(value)
                                return memo
                                , [])


                                // Usage

                                write(chunk([1, 2, 3, 4], 2))
                                write(chunk([1, 2, 3, 4], 4))

                                // For rendering pruposes. Ignore
                                function write (content) document.write(JSON.stringify(content), '</br>')





                                // Chunk function

                                const chunk = (target, size) =>
                                return target.reduce((memo, value, index) =>
                                // Here it comes the only difference
                                if (index % (target.length / size) == 0 && index !== 0) memo.push()
                                memo[memo.length - 1].push(value)
                                return memo
                                , [])


                                // Usage

                                write(chunk([1, 2, 3, 4], 2))
                                write(chunk([1, 2, 3, 4], 4))

                                // For rendering pruposes. Ignore
                                function write (content) document.write(JSON.stringify(content), '</br>')






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Oct 9 '17 at 10:08

























                                answered Apr 15 '15 at 8:23









                                sospedrasospedra

                                7,07131223




                                7,07131223







                                • 2





                                  Wow nice and concise way to do this! Love it! Great job! :-)

                                  – Philippe Monnet
                                  Aug 8 '15 at 22:05






                                • 1





                                  I love this technique, but it's not answering the question. It returns any amount of x-sized chunks, whereas the questions was asking for x amount of evenly-sized chunks.

                                  – Jodi Warren
                                  Jan 21 '16 at 11:53






                                • 3





                                  Love this !!! I've refactored to return evenly-sized chunks function splitArr(arr, n) return arr.reduce(function (a, i) if (a[a.length - 1].length >= arr.length / n) a.push() a[a.length - 1].push(i) return a; , [])

                                  – davide andreazzini
                                  Jul 29 '16 at 12:40












                                • This doesn't answer the question at all, it's about fixed size of chunks, not fixed size of items-per-chunk

                                  – vsync
                                  Oct 20 '16 at 22:43






                                • 2





                                  definitely does not answer the question.

                                  – macdelacruz
                                  Jun 14 '17 at 9:53












                                • 2





                                  Wow nice and concise way to do this! Love it! Great job! :-)

                                  – Philippe Monnet
                                  Aug 8 '15 at 22:05






                                • 1





                                  I love this technique, but it's not answering the question. It returns any amount of x-sized chunks, whereas the questions was asking for x amount of evenly-sized chunks.

                                  – Jodi Warren
                                  Jan 21 '16 at 11:53






                                • 3





                                  Love this !!! I've refactored to return evenly-sized chunks function splitArr(arr, n) return arr.reduce(function (a, i) if (a[a.length - 1].length >= arr.length / n) a.push() a[a.length - 1].push(i) return a; , [])

                                  – davide andreazzini
                                  Jul 29 '16 at 12:40












                                • This doesn't answer the question at all, it's about fixed size of chunks, not fixed size of items-per-chunk

                                  – vsync
                                  Oct 20 '16 at 22:43






                                • 2





                                  definitely does not answer the question.

                                  – macdelacruz
                                  Jun 14 '17 at 9:53







                                2




                                2





                                Wow nice and concise way to do this! Love it! Great job! :-)

                                – Philippe Monnet
                                Aug 8 '15 at 22:05





                                Wow nice and concise way to do this! Love it! Great job! :-)

                                – Philippe Monnet
                                Aug 8 '15 at 22:05




                                1




                                1





                                I love this technique, but it's not answering the question. It returns any amount of x-sized chunks, whereas the questions was asking for x amount of evenly-sized chunks.

                                – Jodi Warren
                                Jan 21 '16 at 11:53





                                I love this technique, but it's not answering the question. It returns any amount of x-sized chunks, whereas the questions was asking for x amount of evenly-sized chunks.

                                – Jodi Warren
                                Jan 21 '16 at 11:53




                                3




                                3





                                Love this !!! I've refactored to return evenly-sized chunks function splitArr(arr, n) return arr.reduce(function (a, i) if (a[a.length - 1].length >= arr.length / n) a.push() a[a.length - 1].push(i) return a; , [])

                                – davide andreazzini
                                Jul 29 '16 at 12:40






                                Love this !!! I've refactored to return evenly-sized chunks function splitArr(arr, n) return arr.reduce(function (a, i) if (a[a.length - 1].length >= arr.length / n) a.push() a[a.length - 1].push(i) return a; , [])

                                – davide andreazzini
                                Jul 29 '16 at 12:40














                                This doesn't answer the question at all, it's about fixed size of chunks, not fixed size of items-per-chunk

                                – vsync
                                Oct 20 '16 at 22:43





                                This doesn't answer the question at all, it's about fixed size of chunks, not fixed size of items-per-chunk

                                – vsync
                                Oct 20 '16 at 22:43




                                2




                                2





                                definitely does not answer the question.

                                – macdelacruz
                                Jun 14 '17 at 9:53





                                definitely does not answer the question.

                                – macdelacruz
                                Jun 14 '17 at 9:53











                                3














                                Old question, but since vanillaJS is not a requirement and so many are trying to solve this with lodash/chunk, and without mistaking what _.chunk actually does, here's a concise + accurate solution using lodash:



                                (Unlike the accepted answer, this also guarantees n columns even if originalArray.length < numCols)



                                import _chunk from 'lodash/chunk'

                                /**
                                * Split an array into n subarrays (or columns)
                                * @param Array flatArray Doesn't necessarily have to be flat, but this func only works 1 level deep
                                * @param Number numCols The desired number of columns
                                * @return Array
                                */
                                export function splitArray(flatArray, numCols)
                                const maxColLength = Math.ceil(flatArray.length/numCols)
                                const nestedArray = _chunk(flatArray, maxColLength)
                                let newArray =
                                for (var i = 0; i < numCols; i++)
                                newArray[i] = nestedArray[i]
                                return newArray



                                The for loop at the end is what guarantees the desired number of "columns".






                                share|improve this answer





























                                  3














                                  Old question, but since vanillaJS is not a requirement and so many are trying to solve this with lodash/chunk, and without mistaking what _.chunk actually does, here's a concise + accurate solution using lodash:



                                  (Unlike the accepted answer, this also guarantees n columns even if originalArray.length < numCols)



                                  import _chunk from 'lodash/chunk'

                                  /**
                                  * Split an array into n subarrays (or columns)
                                  * @param Array flatArray Doesn't necessarily have to be flat, but this func only works 1 level deep
                                  * @param Number numCols The desired number of columns
                                  * @return Array
                                  */
                                  export function splitArray(flatArray, numCols)
                                  const maxColLength = Math.ceil(flatArray.length/numCols)
                                  const nestedArray = _chunk(flatArray, maxColLength)
                                  let newArray =
                                  for (var i = 0; i < numCols; i++)
                                  newArray[i] = nestedArray[i]
                                  return newArray



                                  The for loop at the end is what guarantees the desired number of "columns".






                                  share|improve this answer



























                                    3












                                    3








                                    3







                                    Old question, but since vanillaJS is not a requirement and so many are trying to solve this with lodash/chunk, and without mistaking what _.chunk actually does, here's a concise + accurate solution using lodash:



                                    (Unlike the accepted answer, this also guarantees n columns even if originalArray.length < numCols)



                                    import _chunk from 'lodash/chunk'

                                    /**
                                    * Split an array into n subarrays (or columns)
                                    * @param Array flatArray Doesn't necessarily have to be flat, but this func only works 1 level deep
                                    * @param Number numCols The desired number of columns
                                    * @return Array
                                    */
                                    export function splitArray(flatArray, numCols)
                                    const maxColLength = Math.ceil(flatArray.length/numCols)
                                    const nestedArray = _chunk(flatArray, maxColLength)
                                    let newArray =
                                    for (var i = 0; i < numCols; i++)
                                    newArray[i] = nestedArray[i]
                                    return newArray



                                    The for loop at the end is what guarantees the desired number of "columns".






                                    share|improve this answer















                                    Old question, but since vanillaJS is not a requirement and so many are trying to solve this with lodash/chunk, and without mistaking what _.chunk actually does, here's a concise + accurate solution using lodash:



                                    (Unlike the accepted answer, this also guarantees n columns even if originalArray.length < numCols)



                                    import _chunk from 'lodash/chunk'

                                    /**
                                    * Split an array into n subarrays (or columns)
                                    * @param Array flatArray Doesn't necessarily have to be flat, but this func only works 1 level deep
                                    * @param Number numCols The desired number of columns
                                    * @return Array
                                    */
                                    export function splitArray(flatArray, numCols)
                                    const maxColLength = Math.ceil(flatArray.length/numCols)
                                    const nestedArray = _chunk(flatArray, maxColLength)
                                    let newArray =
                                    for (var i = 0; i < numCols; i++)
                                    newArray[i] = nestedArray[i]
                                    return newArray



                                    The for loop at the end is what guarantees the desired number of "columns".







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited May 22 '17 at 22:11

























                                    answered May 22 '17 at 22:03









                                    JoaoJoao

                                    1,21921431




                                    1,21921431





















                                        2














                                        Recursive approach, not tested.



                                        function splitArray(array, parts, out) 
                                        var
                                        len = array.length
                                        , partLen

                                        if (parts < len)
                                        partLen = Math.ceil(len / parts);
                                        out.push(array.slice(0, partLen));
                                        if (parts > 1)
                                        splitArray(array.slice(partLen), parts - 1, out);

                                        else
                                        out.push(array);







                                        share|improve this answer



























                                          2














                                          Recursive approach, not tested.



                                          function splitArray(array, parts, out) 
                                          var
                                          len = array.length
                                          , partLen

                                          if (parts < len)
                                          partLen = Math.ceil(len / parts);
                                          out.push(array.slice(0, partLen));
                                          if (parts > 1)
                                          splitArray(array.slice(partLen), parts - 1, out);

                                          else
                                          out.push(array);







                                          share|improve this answer

























                                            2












                                            2








                                            2







                                            Recursive approach, not tested.



                                            function splitArray(array, parts, out) 
                                            var
                                            len = array.length
                                            , partLen

                                            if (parts < len)
                                            partLen = Math.ceil(len / parts);
                                            out.push(array.slice(0, partLen));
                                            if (parts > 1)
                                            splitArray(array.slice(partLen), parts - 1, out);

                                            else
                                            out.push(array);







                                            share|improve this answer













                                            Recursive approach, not tested.



                                            function splitArray(array, parts, out) 
                                            var
                                            len = array.length
                                            , partLen

                                            if (parts < len)
                                            partLen = Math.ceil(len / parts);
                                            out.push(array.slice(0, partLen));
                                            if (parts > 1)
                                            splitArray(array.slice(partLen), parts - 1, out);

                                            else
                                            out.push(array);








                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Nov 18 '11 at 21:18









                                            1200012000

                                            1032




                                            1032





















                                                2














                                                Another recursive works quite well, it is less ugly



                                                function nSmaller(num, arr, sliced) ;
                                                if(num === 0)
                                                return sliced;


                                                var len = arr.length,
                                                point = Math.ceil(len/num),
                                                nextArr = arr.slice(point);

                                                mySliced.push(arr.slice(0, point));
                                                nSmaller(num-1, nextArr, mySliced);

                                                return(mySliced);






                                                share|improve this answer



























                                                  2














                                                  Another recursive works quite well, it is less ugly



                                                  function nSmaller(num, arr, sliced) ;
                                                  if(num === 0)
                                                  return sliced;


                                                  var len = arr.length,
                                                  point = Math.ceil(len/num),
                                                  nextArr = arr.slice(point);

                                                  mySliced.push(arr.slice(0, point));
                                                  nSmaller(num-1, nextArr, mySliced);

                                                  return(mySliced);






                                                  share|improve this answer

























                                                    2












                                                    2








                                                    2







                                                    Another recursive works quite well, it is less ugly



                                                    function nSmaller(num, arr, sliced) ;
                                                    if(num === 0)
                                                    return sliced;


                                                    var len = arr.length,
                                                    point = Math.ceil(len/num),
                                                    nextArr = arr.slice(point);

                                                    mySliced.push(arr.slice(0, point));
                                                    nSmaller(num-1, nextArr, mySliced);

                                                    return(mySliced);






                                                    share|improve this answer













                                                    Another recursive works quite well, it is less ugly



                                                    function nSmaller(num, arr, sliced) ;
                                                    if(num === 0)
                                                    return sliced;


                                                    var len = arr.length,
                                                    point = Math.ceil(len/num),
                                                    nextArr = arr.slice(point);

                                                    mySliced.push(arr.slice(0, point));
                                                    nSmaller(num-1, nextArr, mySliced);

                                                    return(mySliced);







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Aug 5 '14 at 16:05









                                                    McsMcs

                                                    154129




                                                    154129





















                                                        1














                                                        Probably the cleaner approach would be the following (without using any other library) :



                                                        var myArray = ;
                                                        for(var i=0; i<100; i++)
                                                        myArray.push(i+1);

                                                        console.log(myArray);

                                                        function chunk(arr, size)
                                                        var chunkedArr = ;
                                                        var noOfChunks = Math.ceil(arr.length/size);
                                                        console.log(noOfChunks);
                                                        for(var i=0; i<noOfChunks; i++)
                                                        chunkedArr.push(arr.slice(i*size, (i+1)*size));

                                                        return chunkedArr;


                                                        var chunkedArr = chunk(myArray, 3);
                                                        console.log(chunkedArr);


                                                        I have created my own array which is to be chunked. You can find the code here



                                                        Also we have a method "chunk" in the lodash library which is of great use. Hope that helps






                                                        share|improve this answer



























                                                          1














                                                          Probably the cleaner approach would be the following (without using any other library) :



                                                          var myArray = ;
                                                          for(var i=0; i<100; i++)
                                                          myArray.push(i+1);

                                                          console.log(myArray);

                                                          function chunk(arr, size)
                                                          var chunkedArr = ;
                                                          var noOfChunks = Math.ceil(arr.length/size);
                                                          console.log(noOfChunks);
                                                          for(var i=0; i<noOfChunks; i++)
                                                          chunkedArr.push(arr.slice(i*size, (i+1)*size));

                                                          return chunkedArr;


                                                          var chunkedArr = chunk(myArray, 3);
                                                          console.log(chunkedArr);


                                                          I have created my own array which is to be chunked. You can find the code here



                                                          Also we have a method "chunk" in the lodash library which is of great use. Hope that helps






                                                          share|improve this answer

























                                                            1












                                                            1








                                                            1







                                                            Probably the cleaner approach would be the following (without using any other library) :



                                                            var myArray = ;
                                                            for(var i=0; i<100; i++)
                                                            myArray.push(i+1);

                                                            console.log(myArray);

                                                            function chunk(arr, size)
                                                            var chunkedArr = ;
                                                            var noOfChunks = Math.ceil(arr.length/size);
                                                            console.log(noOfChunks);
                                                            for(var i=0; i<noOfChunks; i++)
                                                            chunkedArr.push(arr.slice(i*size, (i+1)*size));

                                                            return chunkedArr;


                                                            var chunkedArr = chunk(myArray, 3);
                                                            console.log(chunkedArr);


                                                            I have created my own array which is to be chunked. You can find the code here



                                                            Also we have a method "chunk" in the lodash library which is of great use. Hope that helps






                                                            share|improve this answer













                                                            Probably the cleaner approach would be the following (without using any other library) :



                                                            var myArray = ;
                                                            for(var i=0; i<100; i++)
                                                            myArray.push(i+1);

                                                            console.log(myArray);

                                                            function chunk(arr, size)
                                                            var chunkedArr = ;
                                                            var noOfChunks = Math.ceil(arr.length/size);
                                                            console.log(noOfChunks);
                                                            for(var i=0; i<noOfChunks; i++)
                                                            chunkedArr.push(arr.slice(i*size, (i+1)*size));

                                                            return chunkedArr;


                                                            var chunkedArr = chunk(myArray, 3);
                                                            console.log(chunkedArr);


                                                            I have created my own array which is to be chunked. You can find the code here



                                                            Also we have a method "chunk" in the lodash library which is of great use. Hope that helps







                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Apr 22 '16 at 10:42









                                                            Vaibhav PachauriVaibhav Pachauri

                                                            2,31121329




                                                            2,31121329





















                                                                1














                                                                function splitArray(arr, numOfParts = 10)
                                                                const splitedArray =
                                                                for (let i = 0; i < numOfParts;i++)
                                                                const numOfItemsToSplice = arr.length / 10;
                                                                splitedArray.push(arr.splice(0, numOfItemsToSplice))

                                                                return splitedArray;






                                                                share|improve this answer



























                                                                  1














                                                                  function splitArray(arr, numOfParts = 10)
                                                                  const splitedArray =
                                                                  for (let i = 0; i < numOfParts;i++)
                                                                  const numOfItemsToSplice = arr.length / 10;
                                                                  splitedArray.push(arr.splice(0, numOfItemsToSplice))

                                                                  return splitedArray;






                                                                  share|improve this answer

























                                                                    1












                                                                    1








                                                                    1







                                                                    function splitArray(arr, numOfParts = 10)
                                                                    const splitedArray =
                                                                    for (let i = 0; i < numOfParts;i++)
                                                                    const numOfItemsToSplice = arr.length / 10;
                                                                    splitedArray.push(arr.splice(0, numOfItemsToSplice))

                                                                    return splitedArray;






                                                                    share|improve this answer













                                                                    function splitArray(arr, numOfParts = 10)
                                                                    const splitedArray =
                                                                    for (let i = 0; i < numOfParts;i++)
                                                                    const numOfItemsToSplice = arr.length / 10;
                                                                    splitedArray.push(arr.splice(0, numOfItemsToSplice))

                                                                    return splitedArray;







                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Feb 24 '18 at 8:26









                                                                    StefdelecStefdelec

                                                                    1,10621425




                                                                    1,10621425





















                                                                        0














                                                                        I made it this way, it works...



                                                                        function splitArray(array, parts) 
                                                                        if (parts< array.length && array.length > 1 && array != null)
                                                                        var newArray = ;
                                                                        var counter1 = 0;
                                                                        var counter2 = 0;

                                                                        while (counter1 < parts)
                                                                        newArray.push();
                                                                        counter1 += 1;


                                                                        for (var i = 0; i < array.length; i++)
                                                                        newArray[counter2++].push(array[i]);
                                                                        if (counter2 > parts - 1)
                                                                        counter2 = 0;


                                                                        return newArray;
                                                                        else
                                                                        return array;






                                                                        share|improve this answer



























                                                                          0














                                                                          I made it this way, it works...



                                                                          function splitArray(array, parts) 
                                                                          if (parts< array.length && array.length > 1 && array != null)
                                                                          var newArray = ;
                                                                          var counter1 = 0;
                                                                          var counter2 = 0;

                                                                          while (counter1 < parts)
                                                                          newArray.push();
                                                                          counter1 += 1;


                                                                          for (var i = 0; i < array.length; i++)
                                                                          newArray[counter2++].push(array[i]);
                                                                          if (counter2 > parts - 1)
                                                                          counter2 = 0;


                                                                          return newArray;
                                                                          else
                                                                          return array;






                                                                          share|improve this answer

























                                                                            0












                                                                            0








                                                                            0







                                                                            I made it this way, it works...



                                                                            function splitArray(array, parts) 
                                                                            if (parts< array.length && array.length > 1 && array != null)
                                                                            var newArray = ;
                                                                            var counter1 = 0;
                                                                            var counter2 = 0;

                                                                            while (counter1 < parts)
                                                                            newArray.push();
                                                                            counter1 += 1;


                                                                            for (var i = 0; i < array.length; i++)
                                                                            newArray[counter2++].push(array[i]);
                                                                            if (counter2 > parts - 1)
                                                                            counter2 = 0;


                                                                            return newArray;
                                                                            else
                                                                            return array;






                                                                            share|improve this answer













                                                                            I made it this way, it works...



                                                                            function splitArray(array, parts) 
                                                                            if (parts< array.length && array.length > 1 && array != null)
                                                                            var newArray = ;
                                                                            var counter1 = 0;
                                                                            var counter2 = 0;

                                                                            while (counter1 < parts)
                                                                            newArray.push();
                                                                            counter1 += 1;


                                                                            for (var i = 0; i < array.length; i++)
                                                                            newArray[counter2++].push(array[i]);
                                                                            if (counter2 > parts - 1)
                                                                            counter2 = 0;


                                                                            return newArray;
                                                                            else
                                                                            return array;







                                                                            share|improve this answer












                                                                            share|improve this answer



                                                                            share|improve this answer










                                                                            answered Oct 6 '13 at 18:54









                                                                            TermosferaTermosfera

                                                                            10615




                                                                            10615





















                                                                                0














                                                                                check my version of this array split



                                                                                // divide array
                                                                                Array.prototype.divideIt = function(d)
                                                                                if(this.length <= d) return this;
                                                                                var arr = this,
                                                                                hold = ,
                                                                                ref = -1;
                                                                                for(var i = 0; i < arr.length; i++)
                                                                                if(i % d === 0)
                                                                                ref++;

                                                                                if(typeof hold[ref] === 'undefined')
                                                                                hold[ref] = ;

                                                                                hold[ref].push(arr[i]);


                                                                                return hold;
                                                                                ;





                                                                                share|improve this answer



























                                                                                  0














                                                                                  check my version of this array split



                                                                                  // divide array
                                                                                  Array.prototype.divideIt = function(d)
                                                                                  if(this.length <= d) return this;
                                                                                  var arr = this,
                                                                                  hold = ,
                                                                                  ref = -1;
                                                                                  for(var i = 0; i < arr.length; i++)
                                                                                  if(i % d === 0)
                                                                                  ref++;

                                                                                  if(typeof hold[ref] === 'undefined')
                                                                                  hold[ref] = ;

                                                                                  hold[ref].push(arr[i]);


                                                                                  return hold;
                                                                                  ;





                                                                                  share|improve this answer

























                                                                                    0












                                                                                    0








                                                                                    0







                                                                                    check my version of this array split



                                                                                    // divide array
                                                                                    Array.prototype.divideIt = function(d)
                                                                                    if(this.length <= d) return this;
                                                                                    var arr = this,
                                                                                    hold = ,
                                                                                    ref = -1;
                                                                                    for(var i = 0; i < arr.length; i++)
                                                                                    if(i % d === 0)
                                                                                    ref++;

                                                                                    if(typeof hold[ref] === 'undefined')
                                                                                    hold[ref] = ;

                                                                                    hold[ref].push(arr[i]);


                                                                                    return hold;
                                                                                    ;





                                                                                    share|improve this answer













                                                                                    check my version of this array split



                                                                                    // divide array
                                                                                    Array.prototype.divideIt = function(d)
                                                                                    if(this.length <= d) return this;
                                                                                    var arr = this,
                                                                                    hold = ,
                                                                                    ref = -1;
                                                                                    for(var i = 0; i < arr.length; i++)
                                                                                    if(i % d === 0)
                                                                                    ref++;

                                                                                    if(typeof hold[ref] === 'undefined')
                                                                                    hold[ref] = ;

                                                                                    hold[ref].push(arr[i]);


                                                                                    return hold;
                                                                                    ;






                                                                                    share|improve this answer












                                                                                    share|improve this answer



                                                                                    share|improve this answer










                                                                                    answered Apr 25 '15 at 11:34









                                                                                    hitesh upadhyayhitesh upadhyay

                                                                                    23919




                                                                                    23919





















                                                                                        0














                                                                                        if you know wanna set child_arrays.length then i think this solution best:



                                                                                        function sp(size, arr) //size - child_array.length
                                                                                        var out = ,i = 0, n= Math.ceil((arr.length)/size);
                                                                                        while(i < n) out.push(arr.splice(0, (i==n-1) && size < arr.length ? arr.length: size)); i++;
                                                                                        return out;



                                                                                        call fn:
                                                                                        sp(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) //2 - child_arrat.length



                                                                                        answer:
                                                                                        [1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]






                                                                                        share|improve this answer



























                                                                                          0














                                                                                          if you know wanna set child_arrays.length then i think this solution best:



                                                                                          function sp(size, arr) //size - child_array.length
                                                                                          var out = ,i = 0, n= Math.ceil((arr.length)/size);
                                                                                          while(i < n) out.push(arr.splice(0, (i==n-1) && size < arr.length ? arr.length: size)); i++;
                                                                                          return out;



                                                                                          call fn:
                                                                                          sp(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) //2 - child_arrat.length



                                                                                          answer:
                                                                                          [1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]






                                                                                          share|improve this answer

























                                                                                            0












                                                                                            0








                                                                                            0







                                                                                            if you know wanna set child_arrays.length then i think this solution best:



                                                                                            function sp(size, arr) //size - child_array.length
                                                                                            var out = ,i = 0, n= Math.ceil((arr.length)/size);
                                                                                            while(i < n) out.push(arr.splice(0, (i==n-1) && size < arr.length ? arr.length: size)); i++;
                                                                                            return out;



                                                                                            call fn:
                                                                                            sp(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) //2 - child_arrat.length



                                                                                            answer:
                                                                                            [1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]






                                                                                            share|improve this answer













                                                                                            if you know wanna set child_arrays.length then i think this solution best:



                                                                                            function sp(size, arr) //size - child_array.length
                                                                                            var out = ,i = 0, n= Math.ceil((arr.length)/size);
                                                                                            while(i < n) out.push(arr.splice(0, (i==n-1) && size < arr.length ? arr.length: size)); i++;
                                                                                            return out;



                                                                                            call fn:
                                                                                            sp(2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) //2 - child_arrat.length



                                                                                            answer:
                                                                                            [1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]







                                                                                            share|improve this answer












                                                                                            share|improve this answer



                                                                                            share|improve this answer










                                                                                            answered May 14 '15 at 6:58









                                                                                            miukkimiukki

                                                                                            1,0551113




                                                                                            1,0551113





















                                                                                                0














                                                                                                Just use lodash' chunk function to split the array into smaller arrays https://lodash.com/docs#chunk No need to fiddle with the loops anymore!






                                                                                                share|improve this answer


















                                                                                                • 1





                                                                                                  The question asks how to solve this using vannila js, not using js libraries

                                                                                                  – T J
                                                                                                  Dec 15 '15 at 16:34






                                                                                                • 2





                                                                                                  Thanks for bringing this up. I didn't know lodash had this.

                                                                                                  – Tiago
                                                                                                  Jan 22 '16 at 11:03






                                                                                                • 9





                                                                                                  This also doesn't answer the question. He wants N arrays, not arrays of N elements.

                                                                                                  – mAAdhaTTah
                                                                                                  Feb 9 '16 at 14:53















                                                                                                0














                                                                                                Just use lodash' chunk function to split the array into smaller arrays https://lodash.com/docs#chunk No need to fiddle with the loops anymore!






                                                                                                share|improve this answer


















                                                                                                • 1





                                                                                                  The question asks how to solve this using vannila js, not using js libraries

                                                                                                  – T J
                                                                                                  Dec 15 '15 at 16:34






                                                                                                • 2





                                                                                                  Thanks for bringing this up. I didn't know lodash had this.

                                                                                                  – Tiago
                                                                                                  Jan 22 '16 at 11:03






                                                                                                • 9





                                                                                                  This also doesn't answer the question. He wants N arrays, not arrays of N elements.

                                                                                                  – mAAdhaTTah
                                                                                                  Feb 9 '16 at 14:53













                                                                                                0












                                                                                                0








                                                                                                0







                                                                                                Just use lodash' chunk function to split the array into smaller arrays https://lodash.com/docs#chunk No need to fiddle with the loops anymore!






                                                                                                share|improve this answer













                                                                                                Just use lodash' chunk function to split the array into smaller arrays https://lodash.com/docs#chunk No need to fiddle with the loops anymore!







                                                                                                share|improve this answer












                                                                                                share|improve this answer



                                                                                                share|improve this answer










                                                                                                answered Dec 11 '15 at 15:25









                                                                                                George HerolyantsGeorge Herolyants

                                                                                                50744




                                                                                                50744







                                                                                                • 1





                                                                                                  The question asks how to solve this using vannila js, not using js libraries

                                                                                                  – T J
                                                                                                  Dec 15 '15 at 16:34






                                                                                                • 2





                                                                                                  Thanks for bringing this up. I didn't know lodash had this.

                                                                                                  – Tiago
                                                                                                  Jan 22 '16 at 11:03






                                                                                                • 9





                                                                                                  This also doesn't answer the question. He wants N arrays, not arrays of N elements.

                                                                                                  – mAAdhaTTah
                                                                                                  Feb 9 '16 at 14:53












                                                                                                • 1





                                                                                                  The question asks how to solve this using vannila js, not using js libraries

                                                                                                  – T J
                                                                                                  Dec 15 '15 at 16:34






                                                                                                • 2





                                                                                                  Thanks for bringing this up. I didn't know lodash had this.

                                                                                                  – Tiago
                                                                                                  Jan 22 '16 at 11:03






                                                                                                • 9





                                                                                                  This also doesn't answer the question. He wants N arrays, not arrays of N elements.

                                                                                                  – mAAdhaTTah
                                                                                                  Feb 9 '16 at 14:53







                                                                                                1




                                                                                                1





                                                                                                The question asks how to solve this using vannila js, not using js libraries

                                                                                                – T J
                                                                                                Dec 15 '15 at 16:34





                                                                                                The question asks how to solve this using vannila js, not using js libraries

                                                                                                – T J
                                                                                                Dec 15 '15 at 16:34




                                                                                                2




                                                                                                2





                                                                                                Thanks for bringing this up. I didn't know lodash had this.

                                                                                                – Tiago
                                                                                                Jan 22 '16 at 11:03





                                                                                                Thanks for bringing this up. I didn't know lodash had this.

                                                                                                – Tiago
                                                                                                Jan 22 '16 at 11:03




                                                                                                9




                                                                                                9





                                                                                                This also doesn't answer the question. He wants N arrays, not arrays of N elements.

                                                                                                – mAAdhaTTah
                                                                                                Feb 9 '16 at 14:53





                                                                                                This also doesn't answer the question. He wants N arrays, not arrays of N elements.

                                                                                                – mAAdhaTTah
                                                                                                Feb 9 '16 at 14:53











                                                                                                0














                                                                                                If you can use lodash and would like a functional programming approach, here is what I come up with:



                                                                                                const _ = require('lodash')

                                                                                                function splitArray(array, numChunks)
                                                                                                return _.reduce(_.range(numChunks), (array, result, numChunks, chunkIndex) =>
                                                                                                const numItems = Math.ceil(array.length / numChunks)
                                                                                                const items = _.take(array, numItems)
                                                                                                result.push(items)
                                                                                                return
                                                                                                array: _.drop(array, numItems),
                                                                                                result,
                                                                                                numChunks: numChunks - 1

                                                                                                ,
                                                                                                array,
                                                                                                result: ,
                                                                                                numChunks
                                                                                                ).result






                                                                                                share|improve this answer





























                                                                                                  0














                                                                                                  If you can use lodash and would like a functional programming approach, here is what I come up with:



                                                                                                  const _ = require('lodash')

                                                                                                  function splitArray(array, numChunks)
                                                                                                  return _.reduce(_.range(numChunks), (array, result, numChunks, chunkIndex) =>
                                                                                                  const numItems = Math.ceil(array.length / numChunks)
                                                                                                  const items = _.take(array, numItems)
                                                                                                  result.push(items)
                                                                                                  return
                                                                                                  array: _.drop(array, numItems),
                                                                                                  result,
                                                                                                  numChunks: numChunks - 1

                                                                                                  ,
                                                                                                  array,
                                                                                                  result: ,
                                                                                                  numChunks
                                                                                                  ).result






                                                                                                  share|improve this answer



























                                                                                                    0












                                                                                                    0








                                                                                                    0







                                                                                                    If you can use lodash and would like a functional programming approach, here is what I come up with:



                                                                                                    const _ = require('lodash')

                                                                                                    function splitArray(array, numChunks)
                                                                                                    return _.reduce(_.range(numChunks), (array, result, numChunks, chunkIndex) =>
                                                                                                    const numItems = Math.ceil(array.length / numChunks)
                                                                                                    const items = _.take(array, numItems)
                                                                                                    result.push(items)
                                                                                                    return
                                                                                                    array: _.drop(array, numItems),
                                                                                                    result,
                                                                                                    numChunks: numChunks - 1

                                                                                                    ,
                                                                                                    array,
                                                                                                    result: ,
                                                                                                    numChunks
                                                                                                    ).result






                                                                                                    share|improve this answer















                                                                                                    If you can use lodash and would like a functional programming approach, here is what I come up with:



                                                                                                    const _ = require('lodash')

                                                                                                    function splitArray(array, numChunks)
                                                                                                    return _.reduce(_.range(numChunks), (array, result, numChunks, chunkIndex) =>
                                                                                                    const numItems = Math.ceil(array.length / numChunks)
                                                                                                    const items = _.take(array, numItems)
                                                                                                    result.push(items)
                                                                                                    return
                                                                                                    array: _.drop(array, numItems),
                                                                                                    result,
                                                                                                    numChunks: numChunks - 1

                                                                                                    ,
                                                                                                    array,
                                                                                                    result: ,
                                                                                                    numChunks
                                                                                                    ).result







                                                                                                    share|improve this answer














                                                                                                    share|improve this answer



                                                                                                    share|improve this answer








                                                                                                    edited Jan 13 '18 at 12:56

























                                                                                                    answered Jan 13 '18 at 12:40









                                                                                                    WormieWormie

                                                                                                    65




                                                                                                    65





















                                                                                                        0














                                                                                                        all above might work fine, but what if you have associative array with strings as keys?



                                                                                                        objectKeys = Object.keys;

                                                                                                        arraySplit(arr, n)
                                                                                                        let counter = 0;
                                                                                                        for (const a of this.objectKeys(arr))
                                                                                                        this.arr[(counter%n)][a] = arr[a];
                                                                                                        counter++;







                                                                                                        share|improve this answer



























                                                                                                          0














                                                                                                          all above might work fine, but what if you have associative array with strings as keys?



                                                                                                          objectKeys = Object.keys;

                                                                                                          arraySplit(arr, n)
                                                                                                          let counter = 0;
                                                                                                          for (const a of this.objectKeys(arr))
                                                                                                          this.arr[(counter%n)][a] = arr[a];
                                                                                                          counter++;







                                                                                                          share|improve this answer

























                                                                                                            0












                                                                                                            0








                                                                                                            0







                                                                                                            all above might work fine, but what if you have associative array with strings as keys?



                                                                                                            objectKeys = Object.keys;

                                                                                                            arraySplit(arr, n)
                                                                                                            let counter = 0;
                                                                                                            for (const a of this.objectKeys(arr))
                                                                                                            this.arr[(counter%n)][a] = arr[a];
                                                                                                            counter++;







                                                                                                            share|improve this answer













                                                                                                            all above might work fine, but what if you have associative array with strings as keys?



                                                                                                            objectKeys = Object.keys;

                                                                                                            arraySplit(arr, n)
                                                                                                            let counter = 0;
                                                                                                            for (const a of this.objectKeys(arr))
                                                                                                            this.arr[(counter%n)][a] = arr[a];
                                                                                                            counter++;








                                                                                                            share|improve this answer












                                                                                                            share|improve this answer



                                                                                                            share|improve this answer










                                                                                                            answered Feb 21 '18 at 11:28









                                                                                                            lokerslokers

                                                                                                            1,40911216




                                                                                                            1,40911216





















                                                                                                                -1














                                                                                                                function parseToPages(elements, pageSize = 8) 
                                                                                                                var result = ;
                                                                                                                while (elements.length)
                                                                                                                result.push(elements.splice(0, pageSize));

                                                                                                                return result;






                                                                                                                share|improve this answer


















                                                                                                                • 1





                                                                                                                  Please don't just dump code as an answer. Add an explanation how this addresses the problem of the question.

                                                                                                                  – Mark Rotteveel
                                                                                                                  Dec 10 '18 at 18:28















                                                                                                                -1














                                                                                                                function parseToPages(elements, pageSize = 8) 
                                                                                                                var result = ;
                                                                                                                while (elements.length)
                                                                                                                result.push(elements.splice(0, pageSize));

                                                                                                                return result;






                                                                                                                share|improve this answer


















                                                                                                                • 1





                                                                                                                  Please don't just dump code as an answer. Add an explanation how this addresses the problem of the question.

                                                                                                                  – Mark Rotteveel
                                                                                                                  Dec 10 '18 at 18:28













                                                                                                                -1












                                                                                                                -1








                                                                                                                -1







                                                                                                                function parseToPages(elements, pageSize = 8) 
                                                                                                                var result = ;
                                                                                                                while (elements.length)
                                                                                                                result.push(elements.splice(0, pageSize));

                                                                                                                return result;






                                                                                                                share|improve this answer













                                                                                                                function parseToPages(elements, pageSize = 8) 
                                                                                                                var result = ;
                                                                                                                while (elements.length)
                                                                                                                result.push(elements.splice(0, pageSize));

                                                                                                                return result;







                                                                                                                share|improve this answer












                                                                                                                share|improve this answer



                                                                                                                share|improve this answer










                                                                                                                answered Dec 10 '18 at 17:13









                                                                                                                Vitalii KulykVitalii Kulyk

                                                                                                                63




                                                                                                                63







                                                                                                                • 1





                                                                                                                  Please don't just dump code as an answer. Add an explanation how this addresses the problem of the question.

                                                                                                                  – Mark Rotteveel
                                                                                                                  Dec 10 '18 at 18:28












                                                                                                                • 1





                                                                                                                  Please don't just dump code as an answer. Add an explanation how this addresses the problem of the question.

                                                                                                                  – Mark Rotteveel
                                                                                                                  Dec 10 '18 at 18:28







                                                                                                                1




                                                                                                                1





                                                                                                                Please don't just dump code as an answer. Add an explanation how this addresses the problem of the question.

                                                                                                                – Mark Rotteveel
                                                                                                                Dec 10 '18 at 18:28





                                                                                                                Please don't just dump code as an answer. Add an explanation how this addresses the problem of the question.

                                                                                                                – Mark Rotteveel
                                                                                                                Dec 10 '18 at 18:28











                                                                                                                -3














                                                                                                                If you are using lodash, you can achieve it fairly easily like below:



                                                                                                                import chunk from 'lodash';
                                                                                                                // divides the array into 2 sections
                                                                                                                chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 2); // => [[1,2,3,4,5,6], [7,8,9,10,11]]





                                                                                                                share|improve this answer


















                                                                                                                • 3





                                                                                                                  This is wrong. _.chunk creates arrays of N elements not N arrays. Your example would have an output of 6 arrays with 2 elements in each exept the last one [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]]

                                                                                                                  – Vassilis Barzokas
                                                                                                                  Dec 23 '16 at 11:00











                                                                                                                • thats what the original question is. please read the expected behaviour in the question.

                                                                                                                  – abhisekpaul
                                                                                                                  Mar 14 '17 at 13:38
















                                                                                                                -3














                                                                                                                If you are using lodash, you can achieve it fairly easily like below:



                                                                                                                import chunk from 'lodash';
                                                                                                                // divides the array into 2 sections
                                                                                                                chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 2); // => [[1,2,3,4,5,6], [7,8,9,10,11]]





                                                                                                                share|improve this answer


















                                                                                                                • 3





                                                                                                                  This is wrong. _.chunk creates arrays of N elements not N arrays. Your example would have an output of 6 arrays with 2 elements in each exept the last one [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]]

                                                                                                                  – Vassilis Barzokas
                                                                                                                  Dec 23 '16 at 11:00











                                                                                                                • thats what the original question is. please read the expected behaviour in the question.

                                                                                                                  – abhisekpaul
                                                                                                                  Mar 14 '17 at 13:38














                                                                                                                -3












                                                                                                                -3








                                                                                                                -3







                                                                                                                If you are using lodash, you can achieve it fairly easily like below:



                                                                                                                import chunk from 'lodash';
                                                                                                                // divides the array into 2 sections
                                                                                                                chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 2); // => [[1,2,3,4,5,6], [7,8,9,10,11]]





                                                                                                                share|improve this answer













                                                                                                                If you are using lodash, you can achieve it fairly easily like below:



                                                                                                                import chunk from 'lodash';
                                                                                                                // divides the array into 2 sections
                                                                                                                chunk([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 2); // => [[1,2,3,4,5,6], [7,8,9,10,11]]






                                                                                                                share|improve this answer












                                                                                                                share|improve this answer



                                                                                                                share|improve this answer










                                                                                                                answered Nov 22 '16 at 11:21









                                                                                                                abhisekpaulabhisekpaul

                                                                                                                17313




                                                                                                                17313







                                                                                                                • 3





                                                                                                                  This is wrong. _.chunk creates arrays of N elements not N arrays. Your example would have an output of 6 arrays with 2 elements in each exept the last one [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]]

                                                                                                                  – Vassilis Barzokas
                                                                                                                  Dec 23 '16 at 11:00











                                                                                                                • thats what the original question is. please read the expected behaviour in the question.

                                                                                                                  – abhisekpaul
                                                                                                                  Mar 14 '17 at 13:38













                                                                                                                • 3





                                                                                                                  This is wrong. _.chunk creates arrays of N elements not N arrays. Your example would have an output of 6 arrays with 2 elements in each exept the last one [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]]

                                                                                                                  – Vassilis Barzokas
                                                                                                                  Dec 23 '16 at 11:00











                                                                                                                • thats what the original question is. please read the expected behaviour in the question.

                                                                                                                  – abhisekpaul
                                                                                                                  Mar 14 '17 at 13:38








                                                                                                                3




                                                                                                                3





                                                                                                                This is wrong. _.chunk creates arrays of N elements not N arrays. Your example would have an output of 6 arrays with 2 elements in each exept the last one [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]]

                                                                                                                – Vassilis Barzokas
                                                                                                                Dec 23 '16 at 11:00





                                                                                                                This is wrong. _.chunk creates arrays of N elements not N arrays. Your example would have an output of 6 arrays with 2 elements in each exept the last one [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]]

                                                                                                                – Vassilis Barzokas
                                                                                                                Dec 23 '16 at 11:00













                                                                                                                thats what the original question is. please read the expected behaviour in the question.

                                                                                                                – abhisekpaul
                                                                                                                Mar 14 '17 at 13:38






                                                                                                                thats what the original question is. please read the expected behaviour in the question.

                                                                                                                – abhisekpaul
                                                                                                                Mar 14 '17 at 13:38


















                                                                                                                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%2f8188548%2fsplitting-a-js-array-into-n-arrays%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







                                                                                                                這個網誌中的熱門文章

                                                                                                                What does pagestruct do in Eviews?

                                                                                                                Dutch intervention in Lombok and Karangasem

                                                                                                                Channel Islands