Search code examples
javascriptarraysjavascript-objects

Filter array of objects by multiple values


I want to be able to create a new array of objects by filtering one by multiple search terms

Example:

  const arr = [
  {
      'city': 'Atlanta',
      'state': 'Georgia'
  },
  {
      'city': 'Chicago',
      'state': 'Illinois'
  },
  {
      'city': 'Miami',
      'state': 'Florida'
  }
]

const searchTerms = ['Georgia', 'Florida']

I would like to be able to filter it like this:

arr.filter(obj => obj['state'].includes(searchTerms))

I've found that entering one string with the .includes works, but not an array. I'm open to different logic or even a third party library like lodash or something. I would like to return a new array of objects with only the states that are in the searchterms array


Solution

  • You should call searchTerms.includes on obj.state and not the other way around. So it becomes:

    let result = arr.filter(obj => searchTerms.includes(obj.state));
    

    Which means filter out objects that have thier state property included in the array searchItems.

    Example:

    const arr = [{'city': 'Atlanta', 'state': 'Georgia'}, {'city': 'Chicago', 'state': 'Illinois'}, {'city': 'Miami', 'state': 'Florida'}];
    
    const searchTerms = ['Georgia', 'Florida'];
    
    let result = arr.filter(obj => searchTerms.includes(obj.state));
    
    console.log(result);