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]);

            };
    }
1

3 Answers 3

1
var arrWrap = [];
var steps = 4;
for (var i = 0; i < elements.length; i=i+steps) { 
    arrWrap.push(elements.slice(i,i+steps));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, but I get an error: Uncaught TypeError: elements.slice is not a function.
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>');

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.