Le Moi Le Moi - 7 months ago 13
Javascript Question

Only filter an array in JavaScript when a specific select option is selected

I am trying to enable filtering within React on an array of JSON. I am sorting alphabetically, then I need to filter by category key IF the select dropdown is changed to that category (this is passed via the filter argument on the onChange event).

Then I map over the filtered array, outputting the relevant HTML.

My problem is, how do I essentially skip the filter, if the 'All' option is selected in the select dropdown?
Currently when that is selected, no elements are passed to map and nothing is rendered out.

Thanks :)

renderProduce(orderBy, filter) {
return this.fetchProduce()
.sort(function(a,b) {
return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0);
})
.filter(function(item) {
if ( filter != 'All' ) {
return item.category == filter;
}
})
.map((item, i) => (
<Item key={i} item={item} />
));
}

Answer

You can do that by making the filter callback always return true if the 'All' filter is selected.

    .filter(function(item) {
        return filter === 'All' || item.category == filter
    })