This might be a duplicate but I cant seem to find a stackoverflow question with my exact question. I’m displaying a table of data in the frontend and i’m allowing the user to filter by multiple optional variables. So lets say my data variables are user details in this format:
[
{
firstName = 'bob',
middleName = 'bruh',
lastName = 'bub'
},
.
.
.
{
firstName = 'sam',
middleName = 'marley',
lastName = 'jackson'
}
]
Now im allowing the users to filter by firstName, middleName and LastName. But they are also allowed to filter using only one variable, or a combination of any of the three.
The naive approach that I am using now is to have 7 if statements that filter the array depending on the user input:
so
let filterByFirstName = this.firstNameQuery !== null;
let filterByMiddleName = this.middleNameQuery !== null;
let filterByLastName = this.lastNameQuery !== null;
if(filterByFirstName && !filterByMiddleName && !filterByLastName)
//filter the array only by first name
else if(filterByFirstName && filterByMiddleName && !filterByLastName)
// filter array by first and middle name
.
.
.
else if(filterByFirstName && filterByMiddleName && filterByLastName)
//filter array by first, middle and last name.
So algorithmically its efficient enough, but not so much for the cleanliness of the code as i will be adding more and more variable to filter by.
I have tried creating just one filter statement that will filter depending on the variables supplied but i’m having trouble coding it.
let filterByFirstName = this.firstNameQuery !== null;
let filterByMiddleName = this.middleNameQuery !== null;
let filterByLastName = this.lastNameQuery !== null;
this.displayArray = this.userArray.filter(
user =>
user.firstName === (filterByFirstName ? this.firstNameQuery : 'any String') &&
user.middleName === (filterByMiddleName ? this.middleNameQuery : 'any String') &&
user.lastName === (filterByLastName ? this.lastNameQuery : 'any String')
);
So essentially what i need is a wildcard or the equivalent of any string to put in the filter function, if this is even possible. Thanks in advance 🙂