Difficulty when trying to filter data from fetch Api

Hello everyone, I have problem filtering this data result I got from fetch API… For an example, when the England button is clicked, I want football matches (data) from England be displayed only e.tc

My flawed solution is displayed in the the codepen link below:

Codepen

Well you have several issues here. But the first one is that where you use includes() is not on a string… league.competition is an object. So you need to use res.name.includes(id). Next, id is returning the name of the country in the data-id attribute of a button. For England this is ‘England’. Great, but the matches have ENGLAND in the name. So you have to uppercase your ID if you wish to match it in the names.

Now after this you have some design problems in that you loop through your buttons and add click events. Fine, but then you go to displaying results. Which is done once. When you click a button, the event handler is triggered, but not that display code. I suggest you put your display code in a function you can call. Pass it the results from your filtered data.

I have put together some fixes and ideas that show you how this works. I have included some comments.

Enjoy!

2 Likes

Thanks @Martyr2 , I found your solution clear and helpful … How were you able to assign output = filterResults(data_results); as output variable is not defined in that block scope neither it’s defined as global variable

1 Like

output = filterResults(data_results) IS defining the variable output. You are assigning the results of filterResults to output. I could have just as well done… content.innerHTML = filterResults(data_results) since I am only using output as a place holder and shortly dumping it into innerHTML on the next line.

Now another thing to know about this is that by not using something like let before output the variable is going to be automatically defined on the window object… which I should probably not do. I wasn’t really focused on that. If I did want to update the code, I would dump filterResults right into innerHTML and bypass needing output altogether.

But yes, it is defining the variable because I am using the assignment operator. :slight_smile:

1 Like

@Martyr2 it’s noted… Can you help me with any useful learning material on these array methods: filter and reduce methods… I’m not so confident using them yet.

Map, Filter, and Reduce are the three main techniques that tend to be used.

Here’s a good rundown of those techniques:

Some deeper details about them are found at:

@Paul_Wilkins, I will take my time to go through all the links you listed… Thank you :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.