Unflatten Arrays in groups of four

I have an array that looks like this:

var someArray = ['val1','val2','val3','val4','val5','val6','val7','val8','val9','val10','val11','val12'];

I am trying to find an elegant way using underscorejust convert it to an array of arrays like ...

[['val1','val2','val3','val4'], ['val5','val6','val7','val8'], ['val9','val10','val11','val12']]

Where each index of the new array is a group of four elements from the first array. Is there a simple elegant way to do this with underscore.js.

+4
source share
2 answers

Underline 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));
+9
source

A clean 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"]]
+3
source

All Articles