Reputation: 305
This is my redux state:
people: [
{
id: 1,
name: 'John',
weight: 4500000,
category: 'employee',
brand: 'sony',
sport: 'baseball',
country: 'NZ'
},
{
id: 24,
name: 'Frank',
weight: 7210000,
category: 'admin',
brand: 'sony',
sport: 'basketball',
country: 'Australia'
},
{
id: 10,
name : 'George',
weight: 5800000,
category: 'admin',
brand: 'samsung',
sport: 'basketball',
country: 'NZ'
}
]
I want to filter by multiple parameters and combine these filters, so every time I add a condition the results narrow or expand.
For example, if I want the people who play basketball from NZ, then I would obtain the complete object with id 10.
Then, if I remove the country filter I would obtain the id 10 and 24
What's the way of doing it?
Any idea on how to do it?
Thanks in advance
Upvotes: 0
Views: 1597
Reputation: 1862
I think use lodash
filter works with your need and least code to write:
For filter people playing basketball and country is NZ
. The code should look like:
_.filter(people, { sport:"basketball", country: "NZ" })
For the case you need to filter in many reducers and dont want to repeat yourself of writing these lines. You can write an ultility or adapter function like:
const filterByCreteria = (people, creteria) => _.filter(people, criteria);
You should create a list criteria objects and export it out and whenever you need just import the criterias into your component
Creteria.js
export const BASKET_BALL = { sport: 'basketball' };
export const NEWZELAND = { country: 'NZ' };
// Go on for other criteria
...
...
Iside your component you should import criteria and pass to ultility function:
import { BASKET_BALL, NEWZELAND} from '/path/to/Criteria.js';
// ...
const creteria = {...BASKET_BALL, ...NEWZELAND}
Utils.filterByCreteria(people, criteria);
// ...
Upvotes: 1
Reputation: 9073
In the same reducer you'll need to store a list of the filters which will consist of the key to filter on and the value to filter by. e.g.
[{ key: 'sport', value: 'basketball'}, { key: 'country', value: 'NZ'}]
then you just apply the filters on the list of people:
people.filter(person => filters.every(filter => person[filter.key] === filter.value))
This just checks that each person matches all of the filters
Upvotes: 2