Wiki Viewer shows only last result; I'm stuck please help

Wiki Viewer shows only last result; I'm stuck please help
0

#1

Hey folks. I’ve been trying to solve this problem for a couple of days now but I cannot figure this out.
I’m using foreach loop and want to show all search term results but all it shows is the last result so the other cards with other results don’t even show up.
I’ve also tried it with for loop but I got the exact same result. :confused:
Ignore the search bar appearance. There are some other problems with it :smiley:

Here is my pen https://codepen.io/dknvmlhok/pen/vWRpEq


#2

Your result variables are being overwritten with each loop iteration, so they only contain the last value.


#3

Yes thats what I figured out aswell. What can I do with it?


#4

How about an Array.map instead of an Array.forEach?


#5

Just tried it and nothing seem to change. Creating a new card after each iteration might solve the problem, but I still cannot figure out how to do it :thinking:

$.getJSON(apiUrl,function(data){
   let titles = data[1];
   let texts = data[2];
    
   let titResult = titles.map(function(result){
         $("#card-title").html(result);
     console.log(result);
      });

   let textResult = texts.map(function(result){
         $("#card-text").html(result);
     console.log(result);
      });
    
    $("#card-title, #card-text").append(titResult, textResult);
    
    
    
 });

#6

Well, with map, what you’d be doing is replacing arrays of results with arrays of html elements. So… What would you do with that array to do something to each of it’s values?


#7

Well… if it’s even possible, I would try to use forEach to iterate through each map iteration and then create a function that actually does something to the values.


#8

I eventually did it this way. It does not look nice, but it works!

$.getJSON(apiUrl,function(data){
   let titles = data[1];
   let texts = data[2];
    
   for(let i=0, j=0; i<titles.length, j<texts.length; i++, j++){
     $('<div class="card" id="card">'
       +'<div class="card-body" id="card-body">'
       +'<h4 class="card-title" id="card-title">'+titles[i]+''+'</h4>'
       +'<p class="card-text" id="card-text">'+texts[j]+''+'</p>'
       +'</div>'+'</div>').appendTo("#card-list")
   }
 });

#9

FYI - In case you wanted to use forEach, you could have use the following:

   titles.forEach(function(title,index) {
     $('<div class="card" id="card">'
       +'<div class="card-body" id="card-body">'
       +'<h4 class="card-title" id="card-title">'+title+''+'</h4>'
       +'<p class="card-text" id="card-text">'+texts[index]+''+'</p>'
       +'</div>'+'</div>').appendTo("#card-list")
   });

#10

I see! This way I wasn’t able to find, that’s simple ! Thanks!