0

I have an array which always has a length of 50, which looks like so:

var array = [
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  'item',
  ...
];

What I need to do is loop through that array and create a nested array every 5 items, so the end result will be array containing 10 nested arrays which contain 5 items each, looking something like:

var array = [
  [
    'item',
    'item',
    'item',
    'item',
    'item'
  ],
  [
    'item',
    'item',
    'item',
    'item',
    'item'
  ],
  [
    'item',
    'item',
    'item',
    'item',
    'item'
  ],
  [
    'item',
    'item',
    'item',
    'item',
    'item'
  ],
  ...
];

I've tried quite a few things which always ends up in a complete mess of spaghetti loops, any help would be greatly appreciated. I'm even open to using jQuery if needs be.

3
  • 3
    Post your spaghetti, we're quite the supportive group here. Commented Jun 11, 2015 at 14:16
  • Your comment reads like you only want every fifth element in the first array to have a nested array. Is that right? Commented Jun 11, 2015 at 14:28
  • just splice the array. :) Commented Jun 11, 2015 at 14:31

2 Answers 2

4
var array = ['item','item','item','item','item','item','item','item','item','item','item','item','item'];
var new_arr = [];
while(array.length) new_arr.push(array.splice(0,5));

console.log(new_arr);
Sign up to request clarification or add additional context in comments.

1 Comment

Ended up going with this, worked a treat, thanks a bunch!
0

Just have one for loop.

var temp=[], newArray=[];
for(i=0;i<array.length;i++){
    temp.push(array[i]);
    if(temp.length==size){//size in your case = 5
        newArray.push(temp);
        temp=[];
    }
}

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.