I have an array that is as follows:
var someArray = ['val1','val2','val3','val4','val5','val6','val7','val8','val9','val10','val11','val12'];
I'm trying to figure out some elegant way, using underscore, of simply converting it to an array of arrays like so...
[['val1','val2','val3','val4'], ['val5','val6','val7','val8'], ['val9','val10','val11','val12']]
Where each index of the new array is groups of four elements from the first array. Is there an easy elegant way of doing this with underscore.js.
Underscore, since you asked: (Example)
var i = 4, list = _.groupBy(someArray, function(a, b){
return Math.floor(b/i);
});
newArray = _.toArray(list);
Vanilla JS: (Example)
var newArray = [], size = 4;
while (someArray.length > 0) newArray.push(someArray.splice(0, size));
Pure JavaScript solution, using splice():
Object.defineProperty( Array.prototype, 'eachConsecutive', {
value:function(n){
var copy = this.concat(), result = [];
while (copy.length) result.push( copy.splice(0,n) );
return result;
}
});
var someArray = ['val1','val2','val3','val4','val5','val6','val7','val8','val9','val10','val11','val12'];
var chunked = someArray.eachConsecutive(4);
//-> [["val1","val2","val3","val4"],["val5","val6","val7","val8"],["val9","val10","val11","val12"]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With