C
C
ChrisJonson2016-05-02 18:19:37
JavaScript
ChrisJonson, 2016-05-02 18:19:37

How to make an array filter in React with search and parameters?

There is an array of phones and laptops.

{
    "id": 1,
    "category": "notebooks",
    "brand": "lenovo",
    "title": "Ноутбук Lenovo G50-30",
  },
  {
    "id": 2,
    "category": "notebooks",
    "brand": "lenovo",
    "title": "Ноутбук Lenovo G70-35",
  },
  {
    "id": 10,
    "category": "phones",
    "brand": "samsung",
    "title": "Смартфон Samsung Galaxy S7 32GB Black Onyx",
  },
  {
    "id": 11,
    "category": "phones",
    "brand": "samsung",
    "title": "Смартфон Samsung Galaxy A3 (2016) Black",
  }

There is a search filter in the array
let filteredData = this.state.data.filter((item) =>{
      return item.title.toLowerCase().indexOf(this.props.filterToChild) !== -1;
    });

filteredData is looped through.
How to add filtering by category and brands to this filter, that is, so that in addition to the search there are checkboxes for the categories "Smartphones", "Laptops" and for the brands "lenovo", "samsung"?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lemme, 2016-05-02
@ChrisJonson

I would make a universal filter.

function filterBy(data, field, value) {
  return data.filter(item => item[field] === value);
}

const notebooks = filterBy(this.props.data, 'category', 'notebooks');
const lenovoNotebooks = filterBy(notebooks, 'brand', 'lenovo');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question