tags:

views:

104

answers:

4

I have a JSON list that I want to iterate over, but skip the first entry, like thus:

$.each(
    data.collection,
    function() { DoStuffButOnlyIfNotTheFirstOne(); }
);

Any ideas?

+11  A: 

Is this good enough?

$.each(
    data.collection,
    function(i) {
        if (i > 0)
            DoStuff();
    }
);
Tomas Lycken
Brilliant, thanks
jacko
A: 
$.each(
    data.collection,
    function(i) { if (i>0) DoStuffButOnlyIfNotTheFirstOne(); }
);
Philippe Leybaert
+9  A: 
$.each(
    data.collection,
    function(i) {
        if(i)
            DoStuffButOnlyIfNotTheFirstOne();
    }
);

or, probably more efficiently:

$.each(
    data.collection.slice(1),
    function() {
        DoStuff();
    }
);
chaos
i like that, even though its slightly less readable then accepted solution.
mkoryak
A: 

You can use the good old firstFlag approach:

var firstFlag = true;
$.each(
data.collection,
  function() { 
    if(!firstFlag) DoStuffButOnlyIfNotTheFirstOne(); 
    firstFlag = false;
}

But instead, I'd recommend that you filter your data collection first to remove the first item using a selector.

Jon Galloway
Shouldn't firstFlag = false be after the if statement?
seth
Doh - good catch. Fixed.
Jon Galloway