1

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?

5
  • 6
    for (var i = 0; i < month_array.length; i += 2) { ... } Commented Oct 6, 2014 at 14:38
  • 2
    vanilla for loop, i+=2 ? Commented Oct 6, 2014 at 14:38
  • 2
    You seem to be over complicating it by trying to use .map rather than just a regular old for loop. And not only is your attempt overly complicated, it doesn't actually work. The first item is [Feburary],[March] Commented Oct 6, 2014 at 14:39
  • only month_array[++i]; inisde a regular for is needed! Commented Oct 6, 2014 at 15:02
  • 1
    @Csdtesting: That sounds absolutely horrible in terms of readability and maintainability. Don't mess with the loop variable inside the loop! What's wrong with i+=2 as Regent and Alex both suggested. Commented Oct 6, 2014 at 15:05

4 Answers 4

4

Sometimes .for loop is quite enough! Why don't you try this one inside for loop month_array[++i]; Or simply and better i += 2 at the .for statement:

Demo 1:

var month_array = new Array();
var cList = $('ul.mylist')
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";

for (var i = 0, l = month_array.length; i < l; i+=2) {
var final = month_array[i] + " & " + month_array[i + 1]; 
var li = $('<li/>').html(final).appendTo(cList);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="mylist">
</ul>
Demo 2 - Choose demo 1 is better!:
var month_array = new Array();
var cList = $('ul.mylist')
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";

for (var i = 0, l = month_array.length; i < l; i++) {
  var final = month_array[i] + " & " + month_array[++i];
  var li = $('<li/>').html(final).appendTo(cList);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="mylist">
</ul>

Sign up to request clarification or add additional context in comments.

6 Comments

Modifying the control variable in the loop will make some people angry, i += 2 makes everything clear.
I did that to understand which item is showing for him.I knew that.but anyway it is a strange question. Maybe i did wrong to answer that anyway
You could change to +=2 ;)
Awesome.. I did change to +=2 and i < month_array.length
So, finally, we end up with what we have started 50 minutes ago :) +1 for first demo.
|
1

While I think this is way easier to just use a regular for loop as @Regent suggested in the comments, you could do this with an array.reduce like this:

var months = month_array.reduce(function (pre, curr, idx, arr) {
    if (!(idx % 2)) {
        pre.push([curr, arr[idx + 1]]);
    }
    return pre;
}, []);

console.log(months);

This will give you an array containing six arrays each containing two months, starting with ["January","February"]

Note: in the case of grouping an array with an odd number of items, the last item in your reduced array will be [lastItemInSourceArray, undefined]. You can add logic to handle that case if necessary depending on what you actually need to do. In the case of 12 months, it's obviously not an issue.

Comments

0

Edit, updated. Preserves original array.

Try

v3

var ul = $("<ul>");
var month_array = ["January", "February", "March", "April"
                  , "May", "June", "July", "August"
                  , "September", "October", "November", "December"];

(function arr(m, n) {
    if (ul.children("li").size() < m.length / 2) {
        ul.append("<li>" 
                  + m.slice(n, n + 2).join(" & ") 
                  + "</li>");
                  n = n + 2;
        arr(m, n)
    } else {
        $("body").append(ul);
        console.log(month_array)
    }
}(month_array, 0));

jsfiddle http://jsfiddle.net/guest271314/orrje6qo/4/

1 Comment

Well, it works, but what is the point to overcomplicate the task and to destroy array?
0

The answer u r looking for..!!

<body>
  <div class="listDiv">
    <ul></ul> 
  </div>
</body>



var month_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";
var array=[];
for(var i=1; i<month_array.length; ++i) {
  array[i] = '<li>' + month_array[i-1] + ' & ' +month_array[i] + '</li>';
}

$('.listDiv ul').append(array);

http://jsfiddle.net/raeegzrb/

checkout the output markup as well.

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.