1

How to do filter search in react js / JS? I have a component where I am displaying product details on card e.g (producctId, amounts,natureAndContentsOfContainer,packagingDetails,unitOfMeasure,primaryContainerType,DispensingMode, Ingredient,dosageForm,packSize, productCategoty, productType, strengthPerUnit, tradeName, pic1) and I also want to filter search on Ingredient and dosageForm paramenter only. When I fetch data from API I get this array:

[
  {
    supplier: {
      companyName: "Asad",
      id: "61f0f796cc53c565a15e31a3",
    },
    productId: "6213738798dbb2ecf4c23ddd",
    productDetails: {
      amounts: "%3 v/v",
      barcodePrinted: true,
      dosageForm: "tablet",
      gtinNumber: "09567214",
      api: {
        name: "AMITRIPTYLINE",
        countryOfOrigin: "pakistan",
        approvedBy: "us_fda",
      },
      coloringAgents: { values: Array(0) },
      listOfExcipients: [],
      natureAndContentsOfContainer: "containing 0.5ml solution",
      packSize: "10 tablets",
      packagingDetails: "pack of 3 strips each with 10 tablets",
      pic1: "",
      pic2: "",
      pilLanguage: "english",
      primaryContainerType: "blister",
      strengthPerUnit: "10 mg",
      tradeName: "WELLTRIP",
      unitOfMeasure: "1 k",
      _id: "6213738798dbb2ecf4c23de0",
    },
  },
  {
    supplier: { id: "61f0edffb71dc157de9f7369", companyName: "abc" },
    productId: "623079ef4c177018a57963f0",
    productDetails: {
      DispensingMode: "Pharmacy Only (P)",
      Ingredient:
        " Riboflavin, Selenium, citrus bioflavonoids, copper, Vitamin A, Vitamin B6, Pantothenic acid, Vitamin E, Vitamin B12, Zinc, chromium, carotenoids, Folic acid, biotin, Iron, Magnesium, Manganese, Niacin, Thiamine, Vitamin d, grape seed , Flaxseed Oil, Vitamin C, iodine",
      coloringAgents: { values: Array(0) },
      dosageForm: "Tablet",
      listOfExcipients: [],
      packSize: "30 Tablet",
      preservatives: { values: Array(0) },
      productCategoty: "Registered",
      productType: "cosmatics",
      strengthPerUnit: "Combination",
      tradeName: "WELLKID IMMUNE CHEWABLE ",
      _id: "623079ef4c177018a57963f3",
    },
  },

  {
    supplier: { id: "61f0edffb71dc157de9f7369", companyName: "xyz" },
    productId: "623079ef4c177018a57963ee",
    productDetails: {
      DispensingMode: "Pharmacy Only (P)",
      Ingredient: " lactobacillus acidophilus",
      coloringAgents: { values: Array(0) },
      dosageForm: "Capsule",
      listOfExcipients: [],
      packSize: "15 Capsule",
      preservatives: { values: Array(0) },
      productCategoty: "Registered",
      productType: "cosmatics",
      strengthPerUnit: "Combination",
      tradeName: "LACTOBIOTIX",
      _id: "623079ef4c177018a57963f6",
    },
  },
];

Note: I write only 3 product details. It can be 100+ as well.

Note: Searching parameters are Ingredient & dosageForm.

Now I want that if user search about Ingredient or dosageForm in search bar if data found then only show those arrays that contains searched input data and other data should be neglected.

1
  • Provide your solution which is not working. Commented Apr 3, 2022 at 7:57

4 Answers 4

1

Finally after spending too much time I have resolved the problem. The solution is in javaScript as follows:

const data = [
  {
    supplier: {
      companyName: "Asad",
      id: "61f0f796cc53c565a15e31a3",
    },
    productId: "6213738798dbb2ecf4c23ddd",
    productDetails: {
      amounts: "%3 v/v",
      barcodePrinted: true,
      dosageForm: "tablet",
      gtinNumber: "09567214",
        api: {
          name: "AMITRIPTYLINE",
          countryOfOrigin: "pakistan",
          approvedBy: "us_fda",
        },
        coloringAgents: { values: Array(0) },
        listOfExcipients: [],
      natureAndContentsOfContainer: "containing 0.5ml solution",
      packSize: "10 tablets",
      packagingDetails: "pack of 3 strips each with 10 tablets",
      pic1: "",
      pic2: "",
      pilLanguage: "english",
      primaryContainerType: "blister",
      strengthPerUnit: "10 mg",
      tradeName: "WELLTRIP",
      unitOfMeasure: "1 k",
      _id: "6213738798dbb2ecf4c23de0",
    },
  },
  {
    supplier: { id: "61f0edffb71dc157de9f7369", companyName: "abc" },
    productId: "623079ef4c177018a57963f0",
    productDetails: {
      DispensingMode: "Pharmacy Only (P)",
      Ingredient:
        " Riboflavin, Selenium, citrus bioflavonoids, copper, Vitamin A, Vitamin B6, Pantothenic acid, Vitamin E, Vitamin B12, Zinc, chromium, carotenoids, Folic acid, biotin, Iron, Magnesium, Manganese, Niacin, Thiamine, Vitamin d, grape seed , Flaxseed Oil, Vitamin C, iodine",
        coloringAgents: { values: Array(0) },
      dosageForm: "Tablet",
        listOfExcipients: [],
      packSize: "30 Tablet",
        preservatives: { values: Array(0) },
      productCategoty: "Registered",
      productType: "cosmatics",
      strengthPerUnit: "Combination",
      tradeName: "WELLKID IMMUNE CHEWABLE ",
      _id: "623079ef4c177018a57963f3",
    },
  },

  {
    supplier: { id: "61f0edffb71dc157de9f7369", companyName: "xyz" },
    productId: "623079ef4c177018a57963ee",
    productDetails: {
      DispensingMode: "Pharmacy Only (P)",
      Ingredient: "lactobacillus acidophilus",
      coloringAgents: { values: Array(0) },
      dosageForm: "Capsule",
        listOfExcipients: [],
      packSize: "15 Capsule",
        preservatives: { values: Array(0) },
      productCategoty: "Registered",
      productType: "cosmatics",
      strengthPerUnit: "Combination",
      tradeName: "LACTOBIOTIX",
      _id: "623079ef4c177018a57963f6",
    },
  },
];

const includedParameters = [
  "Ingredient",
  "dosageForm",
];

let value = "copper";
const lowerCaseValue = value.toLowerCase().trim();
if (!lowerCaseValue) {
  console.log("Not lowercase value!");
} else {
  const filterSearch = data.filter((item, index) => {
    return Object.keys(data[index]?.productDetails)?.some((key) => {
    return includedParameters.includes(key)
        ? item?.productDetails[key]?.toString().toLowerCase().includes(lowerCaseValue)
        : false;
    });
  });
  console.log(filterSearch);
}

Sign up to request clarification or add additional context in comments.

Comments

1

Filter by dosageForm

const dosageFormTerm = "Capsule" // dosageForm filter value
products.filter(({ productDetails: { dosageForm } }) => dosageForm === dosageFormTerm)

Filter by Ingredient

const ingredientTerm = "lactobacillus" // ingredient filter value
products.filter(({ productDetails: { Ingredient } }) => Ingredient ? Ingredient.includes(ingredientTerm) : false)

Filter by dosageForm and Ingredient

const searchTerm = {
    dosageForm: "Capsule", // dosageForm filter value
    ingredient: "lactobacillus" // ingredient filter value
}
products.filter(({ productDetails: { dosageForm, Ingredient } }) => Ingredient ? Ingredient.includes(searchTerm.ingredient) && dosageForm === searchTerm.dosageForm : false)

Comments

0

See the implementation below. It's only for the search Ingredients only. You can build same solution for the dosageForm. Single search box can be used for both item search or separate search box for each.

Full code:

import React, {useState} from "react";

let initState = [{
  supplier: {
      companyName: "Asad",
      id: "61f0f796cc53c565a15e31a3",
  },
  productId: "6213738798dbb2ecf4c23ddd",
  productDetails: {
      amounts: "%3 v/v",
      barcodePrinted: true,
      dosageForm: "tablet",
      gtinNumber: "09567214",
      api: {
          name: "AMITRIPTYLINE",
          countryOfOrigin: "pakistan",
          approvedBy: "us_fda",
      },
      coloringAgents: {
          values: Array(0)
      },
      listOfExcipients: [],
      natureAndContentsOfContainer: "containing 0.5ml solution",
      packSize: "10 tablets",
      packagingDetails: "pack of 3 strips each with 10 tablets",
      pic1: "",
      pic2: "",
      pilLanguage: "english",
      primaryContainerType: "blister",
      strengthPerUnit: "10 mg",
      tradeName: "WELLTRIP",
      unitOfMeasure: "1 k",
      _id: "6213738798dbb2ecf4c23de0",
  },
}, {
  supplier: {
      id: "61f0edffb71dc157de9f7369",
      companyName: "abc"
  },
  productId: "623079ef4c177018a57963f0",
  productDetails: {
      DispensingMode: "Pharmacy Only (P)",
      Ingredient: " Riboflavin, Selenium, citrus bioflavonoids, copper, Vitamin A, Vitamin B6, Pantothenic acid, Vitamin E, Vitamin B12, Zinc, chromium, carotenoids, Folic acid, biotin, Iron, Magnesium, Manganese, Niacin, Thiamine, Vitamin d, grape seed , Flaxseed Oil, Vitamin C, iodine",
      coloringAgents: {
          values: Array(0)
      },
      dosageForm: "Tablet",
      listOfExcipients: [],
      packSize: "30 Tablet",
      preservatives: {
          values: Array(0)
      },
      productCategoty: "Registered",
      productType: "cosmatics",
      strengthPerUnit: "Combination",
      tradeName: "WELLKID IMMUNE CHEWABLE ",
      _id: "623079ef4c177018a57963f3",
  },
},
{
  supplier: {
      id: "61f0edffb71dc157de9f7369",
      companyName: "xyz"
  },
  productId: "623079ef4c177018a57963ee",
  productDetails: {
      DispensingMode: "Pharmacy Only (P)",
      Ingredient: " lactobacillus acidophilus",
      coloringAgents: {
          values: Array(0)
      },
      dosageForm: "Capsule",
      listOfExcipients: [],
      packSize: "15 Capsule",
      preservatives: {
          values: Array(0)
      },
      productCategoty: "Registered",
      productType: "cosmatics",
      strengthPerUnit: "Combination",
      tradeName: "LACTOBIOTIX",
      _id: "623079ef4c177018a57963f6",
  },
}, ];

export default function App() {
  const [itm, setItm] = useState();
  const [filteredItms, setfilteredItms] = useState([]);
  return (
    <div>
      <label>Search by Ingredients</label>
      <input type="text" value={itm} onChange={({target})=>{
        let fil = initState.filter(s => {
          if (s.productDetails.Ingredient){
            let theIng = s.productDetails.Ingredient.toLocaleLowerCase();
            let val = target.value.toLocaleLowerCase()
            let fi = theIng.match(val) !== null && theIng.match(val)[0] !== "" && theIng.match(val)[0].length >= 2
            return fi
        } 
      })
        setfilteredItms(fil)
      }}/>
      <p>Search result</p>
      <ul>
        {filteredItms.map(itm => <li>{itm.productId}</li>)}
      </ul>
    </div>
  );
}

1 Comment

It is not working for any type of data. But It is working for above mentioned data set. Thanks for your response.
0

Another way to filter array of objects by multiple fields:

const data = [{"supplier":{"companyName":"Asad","id":"61f0f796cc53c565a15e31a3"},"productId":"6213738798dbb2ecf4c23ddd","productDetails":{"amounts":"%3 v/v","barcodePrinted":true,"dosageForm":"tablet","gtinNumber":"09567214","api":{"name":"AMITRIPTYLINE","countryOfOrigin":"pakistan","approvedBy":"us_fda"},"coloringAgents":{"values":Array(0)},"listOfExcipients":[],"natureAndContentsOfContainer":"containing 0.5ml solution","packSize":"10 tablets","packagingDetails":"pack of 3 strips each with 10 tablets","pic1":"","pic2":"","pilLanguage":"english","primaryContainerType":"blister","strengthPerUnit":"10 mg","tradeName":"WELLTRIP","unitOfMeasure":"1 k","_id":"6213738798dbb2ecf4c23de0"}},{"supplier":{"id":"61f0edffb71dc157de9f7369","companyName":"abc"},"productId":"623079ef4c177018a57963f0","productDetails":{"DispensingMode":"Pharmacy Only (P)","Ingredient":" Riboflavin, Selenium, citrus bioflavonoids, copper, Vitamin A, Vitamin B6, Pantothenic acid, Vitamin E, Vitamin B12, Zinc, chromium, carotenoids, Folic acid, biotin, Iron, Magnesium, Manganese, Niacin, Thiamine, Vitamin d, grape seed , Flaxseed Oil, Vitamin C, iodine","coloringAgents":{"values":Array(0)},"dosageForm":"Tablet","listOfExcipients":[],"packSize":"30 Tablet","preservatives":{"values":Array(0)},"productCategoty":"Registered","productType":"cosmatics","strengthPerUnit":"Combination","tradeName":"WELLKID IMMUNE CHEWABLE ","_id":"623079ef4c177018a57963f3"}},{"supplier":{"id":"61f0edffb71dc157de9f7369","companyName":"xyz"},"productId":"623079ef4c177018a57963ee","productDetails":{"DispensingMode":"Pharmacy Only (P)","Ingredient":"lactobacillus acidophilus","coloringAgents":{"values":Array(0)},"dosageForm":"Capsule","listOfExcipients":[],"packSize":"15 Capsule","preservatives":{"values":Array(0)},"productCategoty":"Registered","productType":"cosmatics","strengthPerUnit":"Combination","tradeName":"LACTOBIOTIX","_id":"623079ef4c177018a57963f6"}}]


const value = "copper";
const filterSearch = data.filter(({ productDetails }) => 
  [productDetails.Ingredient ?? '', productDetails.dosageForm ?? '']
  .join(' ')
  .toLowerCase()
  .includes(value));

console.log(filterSearch);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.