1

I have an array for example: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]

I would like to turn it into the following:

[ [1,2,3,4,5,6],
[7,8,9,10,11,12],
[13,14,15,16,17,18] ]

Basically I need to group every 6 elements, and the arrays of those should be the elements of the 2D array.
I'm not explaining it very well, but the example should be clear.

I've been playing around with some for loops but I could never get the right output. Any help would be appreciated.

Himanshu
  • 4,327
  • 16
  • 31
  • 39
noelj
  • 13
  • 2

3 Answers3

3

The following code will output [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18]]

var items = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
var size = 6, grouped = [];
for ( var i = 0 ; i < items.length ; i+= size ) {
    grouped.push(items.slice(i,i+size));
}
console.log(grouped);

Example on JS Bin

jaggedsoft
  • 3,858
  • 2
  • 33
  • 41
  • 2
    Answering "about to answer" is not very constructive, man. SO is not a race, no need to rush your answer. – Paulo Avelar Nov 18 '15 at 02:38
  • 2
    I was doing something but i quit because it was very similar to what Anik did in his answer and he posted it first but i do like this answer more, +1 – Mi-Creativity Nov 18 '15 at 02:44
  • @PauloAvelar If your goal is to gain reputation, it can definitely become a race ;) That being said, NextLocal: it doesn't help anyone to post an answer that only says that you're "about to answer" (I vaguely remember a meta thread about this too). Either have an answer ready or wait to post until you do! Thanks! – Maximillian Laumeister Nov 18 '15 at 03:43
  • 1
    You guys are right. I was being rediculous. Can't fault me for trying! =8^) – jaggedsoft Nov 18 '15 at 03:50
2

Try like this

var data=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];

var a=-1,temp=[];
data.forEach(function(item,index){
  if(index%6==0){
    temp[++a]=[];
  }
  temp[a].push(item);
});
console.log(temp);

JSFIDDLE

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
0

before post question into stack-overflow search for the same kind of question answered anywhere. There are plenty of question about this algorithm.

based on this answer this is a minimum lines of code.

function arrayChunk(arr){   
    var i,j,chunk = 6, result = [];
    for (i=0,j=arr.length; i<j; i+=chunk)       
        result.push(arr.slice(i,i+chunk));

    return result;
}

you can call this function like

arrayChunk([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]);

result [[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18]]

Community
  • 1
  • 1
Azad
  • 5,144
  • 4
  • 28
  • 56
  • I did look, but I couldn't find the right answer. The one you linked would have helped. I will look more thoroughly next time. Thanks. – noelj Nov 19 '15 at 03:50