-1

This is my array.

const products = [
  {id:1, color:["white","red"], size:["S","M"]},
  {id:2, color:["blue","yellow","white"], size:["S","M","L","XL"]},
  {id:3, color:["green","red"], size:["M"]},
  {id:4, color:["black","green"], size:["L","XL"]},
  {id:5, color:["white","black"], size:["M","L"]},
  {id:6, color:["red","yellow"], size:["S","M"]},
  {id:7, color:["yellow","blue"], size:["L"],
]

There are 2 <Select> elements for user to select what color and size they want. When user select 1 or both filters those filters are parsed in as an object. Like this:

const filters = {color:"red", size:"S"}

or (in case user have selected only 1 filter)

const filters = {color:"red",size:undefined}

I want to filter out which objects meet all the criterias and assign that objects to a new filteredProducts array.

final output should look like this for the const filters = {color:"red", size:"S"} input.

const filteredProducts = [
{id:1, color:["white","red"], size:["S","M"]},
{id:6, color:["red","yellow"], size:["S","M"]}
]

Appreciate all the help.

1 Answers1

0

Try using filter and includes functions as followed:

const products = [
  { id: 1, color: ['white', 'red'], size: ['S', 'M'] },
  { id: 2, color: ['blue', 'yellow', 'white'], size: ['S', 'M', 'L', 'XL'] },
  { id: 3, color: ['green', 'red'], size: ['M'] },
  { id: 4, color: ['black', 'green'], size: ['L', 'XL'] },
  { id: 5, color: ['white', 'black'], size: ['M', 'L'] },
  { id: 6, color: ['red', 'yellow'], size: ['S', 'M'] },
  { id: 7, color: ['yellow', 'blue'], size: ['L'] },
];

const filters = { color: 'red', size: 'S' };

const filteredProducts = products.filter(
  (e) => e.color.includes(filters.color) && e.size.includes(filters.size)
);

console.log(filteredProducts);
Barlo
  • 86
  • 6