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.
-
3Post your spaghetti, we're quite the supportive group here.technophobia– technophobia2015年06月11日 14:16:23 +00:00Commented 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?b_dubb– b_dubb2015年06月11日 14:28:08 +00:00Commented Jun 11, 2015 at 14:28
-
just splice the array. :)Namit Singal– Namit Singal2015年06月11日 14:31:26 +00:00Commented Jun 11, 2015 at 14:31
2 Answers 2
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);
answered Jun 11, 2015 at 14:25
Namit Singal
1,51612 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Tom
Ended up going with this, worked a treat, thanks a bunch!
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=[];
}
}
answered Jun 11, 2015 at 14:21
depperm
10.8k4 gold badges46 silver badges68 bronze badges
Comments
lang-js