Filter multiple values in React
18,320
Solution 1
You are using filtering on the Javascript array level so just extend your criteria:
const filteredUsers = this.state.dataToDisplay.filter(item => {
const query = this.state.search.toLowerCase();
return (
item.name.toLowerCase().indexOf(query) >= 0 ||
item.surname.toLowerCase().indexOf(query) >= 0 ||
item.phone.toLowerCase().indexOf(query) >= 0
)
});
Solution 2
Just add more conditions to filter function
const filteredUsers = this.state.dataToDisplay.filter(item => {
return (
item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) >= 0
|| item.surname.toLowerCase().indexOf(this.state.search.toLowerCase()) >= 0
|| item.phone.toLowerCase().indexOf(this.state.search.toLowerCase()) >= 0;
)
})
Solution 3
You can use something like this code, eg:
const filterField = (search, value) => value.toLowerCase().indexOf(search.toLowerCase()) >= 0;
const orFilter = (search, values) => values.some(filterField.bind(null, search));
const filteredUsers = this.state.dataToDisplay.filter(item =>
orFilter(this.state.search, [item.name, item.surname, phone]);
)
Author by
Martin Nordström
Just trying to learn how to code and later take over the world. My LinkedIn profile
Updated on July 22, 2022Comments
-
Martin Nordström almost 2 years
My filter function here works great, however it only filters the first name (see code). So I was wondering what the "best" way to make it filter by surname and phone too (see image)! Here's my filter at the moment:
const filteredUsers = this.state.dataToDisplay.filter(item => { return ( /*Only firstname!*/item.name.toLowerCase().indexOf(this.state.search.toLowerCase()) >= 0 ) })
Thanks a lot! :D