I have a method that should return a list.
I would like to filter the data by two parameters and not one.
So far I have done the following but that's an unwanted result so I've probably done something wrong
performFilterByRunnerName(
filterByCompetition: string, filterByRunnerName: string
): IRunners[] {
return this.runners
.filter(x => x.runnerName === filterByRunnerName)
.filter(x => x.competitionId === filterByCompetition);
}
use &&
operator
performFilterByRunnerName(
filterByCompetition: string, filterByRunnerName: string
): IRunners[] {
return this.runners
.filter(x => x.runnerName === filterByRunnerName && x.competitionId === filterByCompetition);
}
Doing two filters in sequence means that
- You get a first set of values
- In this set, you create a new set of values
If it isn't what you want, you should probably explain what it is that you are expecting.
But to inform you, you have :
OR
.filter(x => x.runnerName === filterByRunnerName || x.competitionId === filterByCompetition);
AND
.filter(x => x.runnerName === filterByRunnerName && x.competitionId === filterByCompetition);
XOR
.filter(x =>
(x.runnerName === filterByRunnerName && !(x.competitionId === filterByCompetition)) ||
(!(x.runnerName === filterByRunnerName) && x.competitionId === filterByCompetition));
It's hard to know exactly what's going on from your post. But I'll give it a go:
You have a function,
That accepts two values,
and returns an array,
that is first filtered by one value,
which is passed along the pipe,
and is then filtered by the other value.
That's not the same as, "I am filtering an array by two values," which implies the two filters are a simple "&&". They're not. I've seen this subtle (though important) difference cause an issue many times.
A very simple way to go about it: you can just do as many comparisons inside of one filter as you want.
performFilterByRunnerName(
filterByCompetition: string, filterByRunnerName: string
): IRunners[] {
return this.runners
.filter(x => ( x.runnerName === filterByRunnerName && x.competitionId === filterByCompetition ) );
}
If your end game is to "get all objects that match these two criteria" this should run predictably.