Reputation: 49
I have a dynamic list such as
<span class="data-holder" data-month="1" data-year="2015" data-content="mydata"></span>
<span class="data-holder" data-month="2" data-year="2015" data-content="mydata"></span>
<span class="data-holder" data-month="3" data-year="2015" data-content="mydata"></span>
<span class="data-holder" data-month="1" data-year="2014" data-content="mydata"></span>
...
I am trying to display it as lists group by year as following:
<ul>
<p>2015</p1>
<li><span>1<span><span>mydata</span></li>
<li><span>2<span><span>mydata</span></li>
<li><span>3<span><span>mydata</span></li>
</ul>
<ul>
<p>2014</p1>
<li><span>1<span><span>mydata</span></li>
</ul>
I have tried to loop each data-holder, and each time I try to compare the current data-year with previous data-year. If they are equals, I will the push the current data into an array. If they are not, then I will loop the through the array to construct the ul. Well, I find it is more challenging than I thought it would be. I wonder if Jquery have any function such as groupbyproperties()? If it's not, would you mind to help me to achieve my goal? Thank you,
Upvotes: 0
Views: 263
Reputation: 3337
Loop over is good idea. You can create on <ul>
element with class or id which you can grab later and in case it exists just append new record from your input <span>
list. Below you have my solution (JSFiddle). Output <ul>
s have additional id attribute, but I hope it isn't problem for yot.
$('.data-holder').each(function(index, item) {
var year = $(item).attr('data-year');
if ($('ul#year-' + year).length == 0) {
$('body').append('<ul id=year-' + year + '>');
$('ul#year-' + year).append('<p>' + year + '</p>');
}
var data = '<li><span>' + $(item).attr('data-month') + '</span><span>' + $(item).attr('data-content') + '</span></li>';
$('ul#year-' + year).append(data);
});
Upvotes: 2