JavaScript: How to push data in array, into subarrays with an array for each 16 items -
this question has answer here:
- split array chunks 32 answers
i have example data set. want push data array subarray every 16 pieces of data. got started, stuck. ideas?
[ [16 names], [16 names ], [16 names] ]; // output 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 = []; (var = 0; < data.length; i++){ if (i % 16 == 0) sixteengroup.push([i]) } console.log(sixteengroup);
splice (destructive) or slice sounds 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));
Comments
Post a Comment