Filter array of objects by multiple values

爱⌒轻易说出口 提交于 2019-12-12 17:13:35

问题


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


回答1:


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



回答2:


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>



回答3:


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


来源:https://stackoverflow.com/questions/53576285/filter-array-of-objects-by-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!