I want to show 4 random (and different) pics from a flickr user's most recent 200 pics. The code has 3 parts
I've made a request for 200 pics from flickr and I get a Json return which I save in a variable myArray. I run a function on this var that generates a random number (0-200). Using splice, I save the item that corresponds with the random number in a new variable, selArray. This also removes the item from myArray, preventing it from getting randomly selected again. This function runs x times, x being the amount of random numbers you want. This function doesn't quite do what I want it to do. The last part of the code parses the Json. The last part itself works when I use it on myArray but doesn't work on selArray.
This is the problem. After the function getRandoms is finished, selArray contains 4 arrays each holding an object instead of simply holding 4 objects. This is what console shows:
0 [Object { id="...}]
but I want this: (this is what myArray shows)
0 Object { id="...}
So, here's my question: how do I fix this? What am I doing wrong? Remark: I was able to make this code work by replacing item with item[0] in the $.each part of the code.
A second question. Is this good code? I'm specifically interested in performance, speed.
<script>
$(document).ready(function(){
var apikey = '[set api here]';
var userid = '[set id here]';
$.getJSON('http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key='+apikey+'&user_id='+userid+'&per_page=200&format=json&jsoncallback=?',
function(data){
// flickr request ok
if(data.stat == 'ok'){
var myArray = data.photos.photo;
var selArray = new Array;
function getRandoms(number){
for(var i=0; i < number; i++){
var randomNumber = Math.floor(Math.random()*myArray.length);
selArray.push(myArray.splice(randomNumber,1));
}
}
// get random numbers
getRandoms(4);
//look at selArray in console
console.dir(selArray);
//parse json, this works
$.each(selArray, function(i,item){
var purl = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_s.jpg';
var container = '<a target="_blank" href="http://www.flickr.com/photos/'+userid+'/'+item.id+'/"><img class="span4" alt="'+item.title+'" src="' + purl + '"/>';
$(container).appendTo('#images');
});
// flickr request problem
}else{
console.log(" The request to get the array was not good ");
}
});
});
</script>
It seems like what you want is the following:
selArray.push(myArray[randomNumber]);