开发者

Need to group a list of items using jquery

I have a list of items which includes a person and the company they work for. I need to be able to group the list by company, and then display all the people who work for that company.

For example:

<div class="name"> John Doe </div>
<div class="company"> ABC Company </div>
<div class="name"> Jane Smith</div>
<div class="company"> ABC Company </div>

<div class="name"> Bill Williams </div>
<div class="company"> XYZ Compa开发者_StackOverflow中文版ny </div>
<div class="name"> Beth Wilson </div>
<div class="company"> XYZ Company </div>

I'd like the output to show:

ABC Company John Doe Jane Smith

XYZ Company Beth Wilson Bill Williams

Any suggestions on how to group that data??

Thanks.


This should do it ..

  var group = {} // this will keep our entire structure..

  $('.company').each( // for each company element
  function(){
    // grab the name of the company
    var name = $(this).text(); 
    // if it has not been inserted in the group (first time we encounter this company)
    if (!(name in group)) 
      group[name] = []; // we create the company key, and relate it to an array that will hold the persons

    // grab the persons name (the preceding one)
    var person = $(this).prev('.name').text(); 
    // add him to the company list of persons .. 
    group[name].push(person);
  }
  )
    // check for ABC company 
    alert(group[' ABC Company ']);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜