Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a list of dates and year illustrates below:

<ul>
    <li>Jan 2010</li>
    <li>Mar 2010</li>
    <li>Jan 2011</li>
    <li>Jan 2012</li>
    <li>Mar 2012</li>
</ul>

Then i have get each of the listed values using jquery from element and separate month and year such as code below:

$("ul").children("li").each(function(){
    var val = $(this).text();
    var month = val.split(" ")[0]; //get month Jan, Mar
    var year = val.split(" ")[1];  //get year 2010, 2011, 2012

    var arrDate = new Array();

    //do some code here to store the year and the month in array w/c is arrDate
});

So this is a little tricky as the year wont repeat but to store every month with the same year, illustration below:

2010 => Jan
     => Mar
2011 => Jan
2012 => Jan
     => Mar

so the array structure would be something like above, where year will be unique and every month with same year will be stored to its referenced year.

Thanks!

share|improve this question

1 Answer

up vote 4 down vote accepted

In this case you don't need a classic array, but an associative array, that in Javascript translates into a standard object.

var months = {};
$("ul").children("li").each(function(){
    var val = $(this).text().split(" ");
    if (val[1] in months) months[val[1]].push(val[0]);
    else months[val[1]] = [val[0]];
});

Now months is your bidimensional array.

Note: I don't think it's a good idea to retrieve the values you need from the DOM content. Why do you have to do that?

share|improve this answer
Nice answer. I'd +1 but am out of votes for the day – jmort253 May 26 '12 at 19:39
how am i going to extract the month object into array? cause when do alert(months.length) it alerts undefined... thanks – PHP Noob May 27 '12 at 14:10
Of course it's undefined, it's not an array. You didn't say you wanted something like that. But you can use the for...in statement to iterate through the object and count them. Or you can keep the count in a separate variable when you define a new year. – MaxArt May 27 '12 at 14:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.