Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 215
Devon Norris Avatar asked Sep 07 '26 07:09

Devon Norris


1 Answers

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);
like image 154
ibrahim mahrir Avatar answered Sep 09 '26 21:09

ibrahim mahrir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!