Dylan Cross
Dylan Cross

Reputation: 5986

jQuery each json result, less than 6 results

I have a photo upload feature, I return the photos uploaded to do two things with this data, one to prepend them to the photo container, and the second I'm trying to put into a preview the last 6 photos in the JSON array, (which could have 1-100 in it).

This code works fine, however I want it to limit it to the maximum of 6, and also, it needs to take it from the end of the JSON data array.

So if the array had something like: 1,2,3,4,5,6,7,8,9

It should return: 9,8,7,6,5,4

Here's what I use to prepend all of them.

$.each(json, function(i, item) {
    $(".albums #albums li#"+albumID+" .photo-thumbs").prepend("
        <img src='photos/"+json[i]+"_30.jpg' />
    ");
});

Upvotes: 2

Views: 197

Answers (2)

fiestacasey
fiestacasey

Reputation: 627

It would be significantly more efficient to not reverse and slice the array. You can accomplish this with just a normal for loop:

for(var i=json.length-1;i>json.length-7&&i>0;--i)
{
    $(".albums #albums li#"+albumID+" .photo-thumbs").prepend("
<img src='photos/"+json[i]+"_30.jpg' />
");
}

Upvotes: 0

Vigrond
Vigrond

Reputation: 8198

$.each(json.reverse().slice(0,json.length>6 ? 6 : json.length)), function(i, item) {
  $(".albums #albums li#"+albumID+" .photo-thumbs").prepend("
  <img src='photos/"+json[i]+"_30.jpg' />
");

Ref:

reverse() http://www.w3schools.com/jsref/jsref_reverse.asp

slice() http://www.w3schools.com/jsref/jsref_slice_array.asp

Upvotes: 3

Related Questions