0

I'm creating an application in React ES6, where I need to filter a list of products by category and type. I have a list of test product data as follows:

const ProductData = [
  {
    id: 1,
    name: 'Product 1',
    categories: ['Cat 1', 'Cat 2'],
    types: ['Type 1', 'Type 3']
  },
  {
    id: 2,
    name: 'Product 2',
    categories: ['Cat 2', 'Cat 3'],
    types: ['Type 1', 'Type 2']
  },
  {
    id: 3,
    name: 'Product 3',
    categories: ['Cat 1', 'Cat 3'],
    types: ['Type 2', 'Type 3']
  },
];

I need to filter the data by categories and type, using preset variables i.e. Cat 1 and Type 2.

I have the following code however I'm aware it's not functioning correctly as the categories and types are arrays within the objects.

const category = 'Cat 1';
const type = 'Type 2';

// need to filter here by both the category and the type
var results=_.filter(ProductData,function(item){
  return item.types.indexOf({type})>-1;
});

How can I change this so it functions as requires? Any help would be much appreciated.

1
  • What is your expected output? Post that as well in the question.. Commented Apr 15, 2020 at 11:05

4 Answers 4

1

update this logic

var results = ProductData.filter(item => {
  return item.categories.includes(category) && item.types.includes(type)
})
Sign up to request clarification or add additional context in comments.

Comments

0

Use includes()

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

const result = ProductData.filter(
  x => x.categories.includes(category) && x.types.includes(type)
);

const ProductData = [
  {
    id: 1,
    name: "Product 1",
    categories: ["Cat 1", "Cat 2"],
    types: ["Type 1", "Type 3"]
  },
  {
    id: 2,
    name: "Product 2",
    categories: ["Cat 2", "Cat 3"],
    types: ["Type 1", "Type 2"]
  },
  {
    id: 3,
    name: "Product 3",
    categories: ["Cat 1", "Cat 3"],
    types: ["Type 2", "Type 3"]
  }
];
const category = "Cat 1";
const type = "Type 2";

const result = ProductData.filter(x => x.categories.includes(category) && x.types.includes(type));

console.log(result);

Comments

0

You can use the .filter() and .includes methods :

const productData = {...}
const category = 'Cat 1'
const type = 'Type 2'

const results = productData.filter(el => el.categories.includes(category) && el. types.includes(type))

Comments

0

This should work as expected.

const results = ProductData.filter(item => item.categories.includes('Cat 1') && item.types.includes('Type 2'))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.