My mind is drawing a blank right now.. I have an array of months:
var month_array = new Array();
month_array[0] = "January";
month_array[1] = "February";
month_array[2] = "March";
month_array[3] = "April";
month_array[4] = "May";
month_array[5] = "June";
month_array[6] = "July";
month_array[7] = "August";
month_array[8] = "September";
month_array[9] = "October";
month_array[10] = "November";
month_array[11] = "December";
I'm trying to output markup as:
<ul>
<li> January & Feburary </li>
<li> March & April </li>
etc.
</ul>
Looping thru the array isn't a problem but what I cannot figure out right now is an elegant way to loop thru every 2 items in the array..
I'm able to do it by using the below to format the array the way I need it to but I think this isn't a good direction as its redundant.
var months = month_array.map(function(elem,i,arr){
return [elem, (i+1<arr.length) ? arr[i+1] : null];
}).filter(function(elem,i){
return (i%2);
});
Anyone know of the best way to group by 2 items in an array?
for (var i = 0; i < month_array.length; i += 2) { ... }forloop,i+=2?.maprather than just a regular oldforloop. And not only is your attempt overly complicated, it doesn't actually work. The first item is[Feburary],[March]i+=2as Regent and Alex both suggested.