0

For a website I used a grid layout. What I want is to store all items per row inside a row.

I have an overall array that is calling arrWrap = [];. Now I want to create for each row an new array, where I store each time 4 items. So a new array should be created after the third item in a row.

How do I achieve this? I use Javascript for this project.

   var arrPos = [];

   for (var i = 0; i < elements.length; ++i) { 

            arrPos[i] = i;
            console.dir(arrPos[i]);

            if (arrPos[i] > 3) {
                alert(arrPos[i]);

            };
    }
Caspert
  • 4,271
  • 15
  • 59
  • 104
  • Possible duplicate [Javascript Multidimensional Array](http://stackoverflow.com/questions/7545641/javascript-multidimensional-array) – Ragdata Sep 16 '15 at 09:05

3 Answers3

1
var arrWrap = [];
var steps = 4;
for (var i = 0; i < elements.length; i=i+steps) { 
    arrWrap.push(elements.slice(i,i+steps));
}
Salketer
  • 14,263
  • 2
  • 30
  • 58
  • Thanks for your answer, but I get an error: Uncaught TypeError: elements.slice is not a function. – Caspert Sep 16 '15 at 09:20
0

Please use the following code:

var cIndex= 0;
var data=[];
var cars = ["Saab", "Volvo", "BMW", "a", "v", "c", "q"];
for(var i = 0; i <= 3; i++)
{
  cIndex = cIndex + 3;
  var row = cars.slice(cIndex -3,cIndex );
  data.push(row);
}
console.log(data);
Matt
  • 74,352
  • 26
  • 153
  • 180
ARUNRAJ
  • 469
  • 6
  • 15
0

This proposal feature the Array.prototype.reduce and offers two solutions:

  1. Grouped by consecutive elements dataGroupedA
[
    [  0,  1,  2 ],
    [  3,  4,  5 ],
    [  6,  7,  8 ],
    [  9, 10, 11 ],
    [ 12, 13, 14 ]
]
  1. Grouped by the 5th element dataGroupedB
[
    [ 0, 5, 10 ],
    [ 1, 6, 11 ],
    [ 2, 7, 12 ],
    [ 3, 8, 13 ],
    [ 4, 9, 14 ]
]

The calculation of index is the important part. The rest is standard default assignment and pushing the actual element.

var data = Array.apply(Array, { length: 15 }).map(function (_, i) { return i; }),
    dataGroupedA = data.reduce(function (r, a, i) {
        var index = i / 3 | 0;
        r[index] = r[index] || [];
        r[index].push(a);
        return r;
    }, []),
    dataGroupedB = data.reduce(function (r, a, i) {
        var index = i % 5;
        r[index] = r[index] || [];
        r[index].push(a);
        return r;
    }, []);

document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(dataGroupedA, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(dataGroupedB, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392