How do I remove unwanted elements from the Wikipedia API?

How do I remove unwanted elements from the Wikipedia API?
0.0 0

#1

Hey, I am working on the “Build a Wikipedia Viewer” project. Everything works fine except when I want to search certain phrases on the search form, the Wikipedia API will return one good item and the rest of the items will return “undefined”.

How would I build a filter into my for loop to exclude any data that is labeled as “undefined” so that it does not show up in my results section?

Here is my code: https://codepen.io/JayDevelopment/pen/LmeLoz?editors=1010

To get an example of the “undefined” results that I am getting, try searching for “beautiful kitty” in the search form. It comes up with one valid entry and description, but the rest all return “undefined.”

I am thankful for all help :slight_smile:


#2

instead of looping 9 times statically , loop only for the amount of results you get back from the api , i.e.

change your loop header from:
for (var i = 0; i <= 9; i++)

to:
for (var i = 0; i < data[1].length; i++)


#3

Thats because for your search word “Beautiful Kitty” , the api returns only one search item.

In your search Program you have hard coded your loop to iterate 10 times.

After successfully displaying the first search result the loop goes for the 2nd one but it does not exist and when you access an element of something that does not exists it undefined.

You can try with just “Kitty” and it displays the 10 results.

So in your case you can do something like:

var len = data[1].length > 10 ? 10: data[1].length;
for (var i = 0; i < len; i++)

The above code will run max 10 times but if the results are less than 10 than the loop will run that many number of times therefore limiting your results to 10 items


#4

You both are gentlemen and scholars :slight_smile: Thanks for the help and great explanations. Cheers!