I'm trying to figure out how optimize my code away from countless if/else statements.
My current code is:
jQuery.each(val, function (i, data) {
//Secret Rare
if(data.card_variations[0].card_rarity == 'Secret Rare'){
secretcount++;
jQuery('.secret-cards').append('<figure><img src="'+data.card_img+'" title="'+data.card_name+'" alt="'+data.card_name+'"><figcaption>'+data.card_variations[0].card_code+'<figcaption></figure>');
}
//Ultra Rare
if(data.card_variations[0].card_rarity == 'Ultra Rare'){
ultracount++;
jQuery('.ultra-cards').append('<figure><img src="'+data.card_img+'" title="'+data.card_name+'" alt="'+data.card_name+'"><figcaption>'+data.card_variations[0].card_code+'<figcaption></figure>');
}
//Super Rare
if(data.card_variations[0].card_rarity == 'Super Rare'){
supercount++;
jQuery('.super-cards').append('<figure><img src="'+data.card_img+'" title="'+data.card_name+'" alt="'+data.card_name+'"><figcaption>'+data.card_variations[0].card_code+'<figcaption></figure>');
}
//Rare
if(data.card_variations[0].card_rarity == 'Rare'){
rarecount++;
jQuery('.rare-cards').append('<figure><img src="'+data.card_img+'" title="'+data.card_name+'" alt="'+data.card_name+'"><figcaption>'+data.card_variations[0].card_code+'<figcaption></figure>');
}
//ShortPrint
if(data.card_variations[0].card_rarity == 'Short Print'){
shortprintcount++;
jQuery('.shortprint-cards').append('<figure><img src="'+data.card_img+'" title="'+data.card_name+'" alt="'+data.card_name+'"><figcaption>'+data.card_variations[0].card_code+'<figcaption></figure>');
}
//Common
if(data.card_variations[0].card_rarity == 'Common'){
commoncount++;
jQuery('.common-cards').append('<figure><img src="'+data.card_img+'" title="'+data.card_name+'" alt="'+data.card_name+'"><figcaption>'+data.card_variations[0].card_code+'<figcaption></figure>');
}
});
As you can see, this is a mess of if/else statements checking for specific rarities and appending to a div depending on the current rarity. There are over 25 different rarities so I figured I can't keep going this way and I'd also need to accommodate every rarity going forward manually through code. I'm also running a count for each to output how many they are.
Is there an optimal way of assigning variables for the counters and dynamically create div class names depending on the result?
EDIT: Maybe an optimal method would be creating an array of all rarities. Since this would still require manual updating, maybe I can query the database through PHP to get all rarities and then fill this array...