Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unflatten Arrays into groups of fours [closed]

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.

like image 799
erichrusch Avatar asked Nov 28 '13 04:11

erichrusch


2 Answers

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));
like image 128
The Alpha Avatar answered Sep 21 '22 17:09

The Alpha


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"]]
like image 31
Phrogz Avatar answered Sep 20 '22 17:09

Phrogz