简体   繁体   中英

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

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

If you're interested in a solution using Ramda :

 const cities = [ { 'city': 'Atlanta', 'state': 'Georgia' }, { 'city': 'Chicago', 'state': 'Illinois' }, { 'city': 'Miami', 'state': 'Florida' } ]; const findCities = (search, cities) => { const predicate = R.flip(R.includes)(search); return R.filter(R.compose(predicate, R.prop('state')), cities); }; console.log( findCities(['Georgia', 'Florida'], cities) ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script> 

Another approach you could take here is to utilize Map which would have consistent retrieval times:

 const arr = [ { 'city': 'Atlanta', 'state': 'Georgia' }, { 'city': 'Chicago', 'state': 'Illinois' }, { 'city': 'Miami', 'state': 'Florida' } ] const searchTerms = ['Georgia', 'Florida'] const searchMap = arr.reduce((r,c) => (r.set(c.state, c),r), new Map()) console.log(searchTerms.map(x => searchMap.get(x))) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM