Home > Back-end >  React applying filter to array object
React applying filter to array object

Time:08-29

Im creating a filtration in the E-commerce project. I have data like

const gender = ["male"]
const brand = ["adidas","nike"]
const price =[100]
//note: gender,brand,price are not static array, it can single element or more than that.

const allProducts = [
{brand:"puma",gender:"male",price:50},
{brand:"nike",gender:"male",price:90},
{brand:"adidas",gender:"female",price:110},
{brand:"adidas",gender:"male",price:95},]

Now, I want to filter all products based on gender, brand, and price. I should get all the products having gender male with brand Adidas and Nike and price less than 100.

I have achieved the result for the brand alone, like this

const[filteredprod,setFilteredprod]=useState()

allProducts.forEach((value)=>{
            for(var i=0;i<brand.length;i  ){
            if(value.brand===brand?.[i])
            {setFilteredProd = value
            )}}
      })

But I want to do to brand gender price simultaneously and get the product. How can I do that? Thanks!!

CodePudding user response:

allProducts.filter((item)=>(item.brand === 'adidas' || item.brand === 'nike') && item.price<100 && item.gender === 'male');

For dynamically checking the condition,

allProducts.filter((item)=>brand.includes(item.brand)&& item.price<price[0] && gender.includes(item.gender));

CodePudding user response:

You can add another condition to your if statement within your forEach loop.

allProducts.forEach((value)=>{
            for(var i=0;i<brand.length;i  ){
            if(value.brand===brand?.[i] && value.gender === 'male' && value.price <100)
            {setFilteredProd = value
            )}}
      })

However the more standard practice would be to use the array method filter.

allProducts.filter(({ brand, price, gender) => (brand === 'adidas' || brand === 'nike') && price < 100 && gender === 'male');

CodePudding user response:

Try this

const gender = ["male"]
const brand = ["adidas", "nike"]
const price = [100]

const allProducts = [{
    brand: "puma",
    gender: "male",
    price: 50
  },
  {
    brand: "nike",
    gender: "male",
    price: 90
  },
  {
    brand: "adidas",
    gender: "female",
    price: 110
  },
  {
    brand: "adidas",
    gender: "male",
    price: 95
  },
]

console.log(allProducts.filter(product => {
      if (product.gender === gender[0] && 
      product.price < price[0] &&
      (product.brand === brand[0] || product.brand === brand[1])) {
          return true
        }
        return false
      }))

  • Related