Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter multiple values in React

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
  )
})

And here's the image: enter image description here

Thanks a lot! :D

like image 216
Martin Nordström Avatar asked Jul 27 '17 20:07

Martin Nordström


2 Answers

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
  )
});
like image 87
Samich Avatar answered Sep 29 '22 16:09

Samich


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;
          )
        })
like image 31
Kamil Socha Avatar answered Sep 29 '22 16:09

Kamil Socha