Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run each for a class but once for group

I have a lot of elements with the same class. These elements are divided into groups by means of attribute "data-xxx"

<div class="myclass" data-n="group1"></div>
<div class="myclass" data-n="group1"></div>
<div class="myclass" data-n="group1"></div>
.... 
<div class="myclass" data-n="group2"></div>
<div class="myclass" data-n="group2"></div>
...
<div class="myclass" data-n="group3"></div>
...
...

How to perform a function on each item, but only once in each group using something like this?

$('.myclass').each(function(){

/// My function

});
like image 570
Aleksov Avatar asked Dec 29 '12 01:12

Aleksov


3 Answers

Working example: http://jsfiddle.net/5sKqU/1/

$(document).ready(function() {
    var group = {}; //an object that we're going to use as a hash  
    $('.myclass').each(function(){ 
        if (group[$(this).attr('data-n')] != true) {
            group[$(this).attr('data-n')] = true;

            //do something here once per each group
            alert('Group: '+ $(this).attr('data-n'));
        }
    }); 
});

I'm assuming that you only need this to run once on page load. If you could share more about your requirements, I can show you what changes you'll need to make.

like image 162
Elliot B. Avatar answered Nov 03 '22 07:11

Elliot B.


Something like this maybe :

var groups = {};
$('.myclass').each(function(i, el) {
    var n = $(el).data('n');
    if(!groups[n]) {
        groups[n] = $();
    }
    groups[n] = groups[n].add(el);
});

//At this point the object `groups` has one property per group, 
//each value being a jquery collection comprising members of the group.

//Now the world's your oyster. You can loop through the groups 
//with full access to each group's members if necessary.
$.each(groups, function(groupName, jq) {
    //my function
});
like image 24
Beetroot-Beetroot Avatar answered Nov 03 '22 06:11

Beetroot-Beetroot


You can set a certain HTML attribute on all group elements after processing the first one. After that, you can check the value of that attribute:

$('.myclass').each(function(){

  if($(this).attr("processed")!="true") {
      // process...
      $("[data-n=" + $(this).attr("data-n")).attr("processed", "true");
  } else {
     // skip, or do something else with the element
  }

});
like image 1
Sych Avatar answered Nov 03 '22 05:11

Sych