3

I am passing an array through a for loop in jQuery. However, order of the array elements is random after each pass. It does not follow the original element position while displaying the array in html. The order is important as I want to match them with another array output. Here is the code:

$(document).ready(function(){

 var streams = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
 var name = [];
 var cLogo =[];

  for (var j = 0; j < streams.length; j++) { 
    $.getJSON("https://api.twitch.tv/kraken/users/" + streams[j]+"?client_id=z4tearbiduwua797pngirp8texyqik",function(c){
   name[j] = c.display_name;
   cLogo[j] = c.logo;
     if(cLogo[j]==null){
 cLogo[i]="http://www.freeiconspng.com/uploads/no-image-icon-32.png";
    }

 $('#name').append('<div><p>'+name[j]+'</p></div>'); 
 $('#logo').append("<div><img src='"+cLogo[j]+"'></div>");
   });            
    };
});
f_haque
  • 31
  • 2

1 Answers1

-1

.getJSON is an asynchronous call so even though you may make calls in an order it does not guarantee a response in the same order.

You can only guarantee this if you make a call, wait for the response and then make the next call

Carlos Alves Jorge
  • 1,919
  • 1
  • 13
  • 29