简体   繁体   中英

how to make grouping in list using jquery?

I want to make sorted group in jquery here is my code https://jsbin.com/xabohupuzu/edit?html,js,output

$(function(){

  var data =['c','d','c','abc','dee','pu','gu']
          function showItemsInList(data, element){
            var str=''
           for(var i=0;i<data.sort().length;i++){
             str+='<li>'+data[i]+'</li>';
           }
            element.append(str);

        }
  showItemsInList(data,$('.abc ul'))

}) 

output

<ul>
<li>abc</li>
<li>c</li>
<li>c</li>
<li>d</li>
<li>dee</li>
<li>gu</li>
<li>pu</li>
</ul>

Expected output

 <ul>
      <li> A---D</li>
       <li>abc</li>
        <li>c</li>
        <li>c</li>
         <li>d</li>
         <li>dee</li>
        <li> E---I</li>
          <li>gu</li>
       <li> J---P</li>
          <li>pu</li>
       <li> Q---Z</li>
       </ul>

I am able to sort my data.But I want to know I will make group in jquery

You could group the data in advance by using an array for the last letter of the group and an array with all groups for the result.

 var data = ['c', 'd', 'c', 'abc', 'dee', 'pu', 'gu'], groups = ['A--D', 'E--I', 'J--P', 'Q--Z'], groupIndex = 0, result = ''; result += '<ul>'; result += '<li>' + groups[groupIndex] + '</li>'; data .sort() .forEach(function (s) { if (s[0].toLowerCase() > groups[groupIndex].slice(-1).toLowerCase()) { result += '<li>' + groups[++groupIndex] + '</li>'; } result += '<li>' + s + '</li>'; }); while (++groupIndex < groups.length) { result += '<li>' + groups[groupIndex] + '</li>'; } result += '</ul>'; document.body.innerHTML += result; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM