Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMartin Coutts
18,154 Pointsfilter array in React
I have 2 arrays, a list of countries and then a list of football competitions. The goal is that the user will select the country from a select. Once this happens the id of that country is fed to state, I have got this working. Once the state has changed I want to execute a function which will filter through the competitions and gather all of the ones with the same area code.
handleCountrySelect = value => {
this.setState({ selectedCountryId: value }, () =>
this.filterCompetitions()
);
console.log(value);
};
filterCompetitions = () => {
let selectedCountryId = this.state.selectedCountryId;
let filteredCompetitions = this.state.competitions.filter(function(
competition
) {
return competition.area.id === selectedCountryId;
});
console.log(selectedCountryId);
console.table(this.state.competitions);
console.log(filteredCompetitions);
};
If I give it an id that matches it works, however when I try to use the selectedCountryId variable it just returns an empty array even though the variable is correct.
1 Answer
Margareta György
7,212 PointsHello :) maybe you already got it working. If not try something like this: You don't have to put the filtering inside a function, you could just have it in render()
```let filteredCompetitions = this.state.competitions && this.state.competitions.filter(competition => competition.area.id === selectedCountryId)
```