lundi 10 juillet 2017

Reactjs Filtering a huge array of objects best practices

in a given app, lets say i have an array that hold 100,000+ object.

objects look like following

let collection = [{
  name:'name',
  price: 10,
  group_id: 1
},
{
  name:'name 2',
  price: 8,
  group_id: 2
},
];

now lets say i have a view which show all 100,000 object, and allow users to filter list by price range or group_id.

--given that such list can be a static list loaded from remote json, or a redux saved collection.

what is best method to filter this filters using price & group filters ?

my first thinking was to keep another array called "filtered_list" in the state of parent component, and when ever a filter change, the filtered_list will reconstruct by filtering parent Collection (looping 100,000+ object again).

but this look not so performant, so i consider may be i should write some logic that decied if the new filter should use the already filtered_list or use parent collection

example :- if group_filter was group_id = 1, then a price filter was added then i should filter only filtered_list, since all inputs of group_1 is already in filtered_list, otherwise if group_id changed from 1 -> 2, then i must refilter the whole big collection, because filtered_list doesnot contain group_id =2 items, its on collection only...

this bring me to another problem.. where should i maintain the filtered_list variable ?

if i added it to redux store, this violate princible of redux that store should only hold information needed to build data, and not calculated data.

const App = props =><div>
<aside>
 <Filtes />
</aside>
<article>
  {props.collection.map(item=><label>item.name</label>)}
</article>
</div>

export default connect( ({collection})=>({collection}) )(App)

Aucun commentaire:

Enregistrer un commentaire