1

I need to get results from firstname or lastname, current behaviour gives me results from firstname only. Or a better approach to this using filter() :) should not be case sensitive too

const people = [
      { firstName: 'Bob', lastName: 'Smith', status: 'single' },
      { firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
      { firstName: 'Jim', lastName: 'bob', status: 'complicated' },
    ]

    const searchString = 'bob'

    const found = people.filter(
      (person) => new RegExp(searchString, 'i')
        .test(
          person.firstName || person.lastName
          ))

    console.log(found)

3 Answers 3

2

The || operator returns the first argument that is truthy (not false, null, undefined, 0 or ""), so this searches for bob in person.firstName only.

You need to do two separate searches. To avoid repeating yourself, store the regexp object in a variable:

    const searchString = 'bob'
    const regexp = new RegExp(searchString, 'i')

    const found = people.filter(
      (person) => regexp.test(person.firstName) || regexp.test(person.lastName)
    )

    console.log(found)
Sign up to request clarification or add additional context in comments.

5 Comments

it's not just a case of "repeating yourself" - the original code would create a brand new RegExp object for every element in the array.
Premature optimization is the root of all evil.
most refactoring of this nature will also lead to optimisation.
@Thomas how about if I search Bob Smith it returns nothing....how can I combine the two terms in search?
@BizMAN that's a separate question.
0

const people = [
      { firstName: 'Bob', lastName: 'Smith', status: 'single' },
      { firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
      { firstName: 'Jim', lastName: 'bob', status: 'complicated' },
    ]

    const searchString = 'bob'

    const found = people.filter(person =>
      (person.firstName.toLowerCase().includes(searchString) ||
       person.lastName.toLowerCase().includes(searchString))
    )

    console.log(found)

Alternative solution without using Regex is by converting to lowercase using toLowerCase and using includes to search of substring existence

1 Comment

filter functions should return true or false, not the object. It works the way you wrote it, but is a bit unexpected.
0

Or use reduce

const found = people.reduce((acc, n) => {
  if (
    n.firstName.toLowerCase() === searchString
    || n.lastName.toLowerCase() === searchString
   ) {
    acc[n] = acc.push(n);
  }
  
  return acc;
}, []);

1 Comment

How does this perform compared to regex solutions?

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.