Search code examples
javascriptarraysnested-loops

JavaScript: How to push data in array, into subarrays with an array for each 16 items


I have an example data set. I want to push this data into an array with a subarray for every 16 pieces of data. I got started, but am stuck. Any ideas?

[ [16 names], [16 names ], [16 names] ]; // This is the output I want.

var data = ["Michael", "Marc", "John", "David", "Nick", "Mom", "Al", "Marlana", "Max", 
            "Scooter", "Pat", "George", "Lynne", "Tatyana", "Kim", "Kerry", "Enza", "Matt",
            "Liz", "Linda", "Ryan",
            "Ed", "Frank", "Christine", "Bill", "Jack", "Jill", "Joe", "Harry", "Red",
            "Fred", "Iggy", "Brian", "Bob", "Paul", "Gil", "Damian", "Kip", "Phil", "Curtis", "Aly",
           "Richard", "Robin", "Grant", "Ian", "Raptor", "T-Rex", "Stegosaurux", "Triceratops", "Compy"]


var sixteengroup = [];

for (var i = 0; i < data.length; i++){
  if (i % 16 == 0) sixteengroup.push([i])
}


console.log(sixteengroup);

Solution

  • Splice (destructive) or slice sounds like a good idea

    var data = ["Michael", "Marc", "John", "David", "Nick", "Mom", "Al", "Marlana", "Max","Scooter", "Pat", "George", "Lynne", "Tatyana", "Kim", "Kerry", "Enza", "Matt","Liz", "Linda", "Ryan", "Ed", "Frank", "Christine", "Bill", "Jack", "Jill", "Joe", "Harry", "Red", "Fred", "Iggy", "Brian", "Bob", "Paul", "Gil", "Damian", "Kip", "Phil", "Curtis", "Aly", "Richard", "Robin", "Grant", "Ian", "Raptor", "T-Rex", "Stegosaurux", "Triceratops", "Compy"]
    
    function chunk(source,size) { // non-destructive
      var arrofarr=[], cnt=0;
      while (cnt < source.length) { 
        arrofarr.push(source.slice(cnt,cnt+size)); 
        cnt+= arrofarr[arrofarr.length-1].length;
      }
      return arrofarr;
    }  
    console.log(chunk(data,16));
    
    // ----------------------------------
    
    function chunkie(source,size) { // destructive
      var arrofarr=[];
      while (source.length) { arrofarr.push(source.splice(0,size)); }
      return arrofarr;
    }
    console.log(chunkie(data,16));