10

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

3 Answers 3

21

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
  )
});
Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't that go agains the DRY principle? Thanks for answering tho! :D
You can create a function where you will normalize to lower case and then call it for each attribute you have - that's code optimization :). Something like ignoreCaseCompare(value1, value2)
3

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

Comments

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]);
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.