My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Filter My Array / JSON Data Based on Multiple Criteria in JavaScript?

Mustafa's photo
Mustafa
·Feb 20, 2020

Hey there,

I want to make people able to search an article database with multiple criteria(s). It's a little bit different to handle because:

  • Some includes more than 1 value (like active substances: ["actSubst1", "actSubs2"])
  • Some values are repeating (retrospective: "1" for "true; ward_focused: "1" for true (again))

Here's my data, it's OK if you convert it into an array and work on it,

json

[
 {
  "title": "Real-world evidence of high-cost drugs for metastatic melanoma",
  "url": "https://.../Suppl_1/A5.1",
  "filters": {
    "retrospective": "1",
    "ward_focused": "2",
    "indication_focused": "1",
    "active_substance": "2"
  }
 },
 {
  "title": "Real-world safety and tolerability of the recently commercialised palbociclib",
  "url": "https://.../Suppl_1/A223.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "1",
    "indication_focused": "2",
    "active_substance": "Palbociclib"
  }
 },
 {
  "title": "Cost-effectiveness of morphine versus fentanyl in managing ventilated neonates",
  "url": "https://.../Suppl_1/A7.3",
  "filters": {
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": ["Morphine", "Fentanyl"]
  }
 },
 {
  "title": "Chemical risk assessement in a quality control laboratory",
  "url": "https://.../Suppl_1/A9.2",
  "filters": {
    "retrospective": "2",
    "ward_focused": "2",
    "indication_focused": "2",
    "active_substance": "2"
  }
 },
 {
  "title": "The economic burden of metastatic breast cancer in Spain",
  "url": "https://.../27/1/19",
  "filters":{
    "retrospective": "1",
    "ward_focused": "1",
    "indication_focused": "1",
    "active_substance": "2"
  }
 }
]

And here's my query:

const selectedFilters = {
      retrospective: ["1"],
      ward_focused: ["2"],
      indication_focused: ["1"],
      active_substance: []
  };

Simple solutions did not work for these two reasons:

  1. I'm using ["1"] and ["2"] for the boolean data, same value (e.g. ["1"]) repeats itself inside a profile,
  2. There may be more than one value ( e.g. "active_substance": ["Morphine", "Fentanyl"] )

I'm open to work on both as JSON and array for my data. Also I may modify the "1" -"2" structure for my boolean data types. You may also change the data structure if needed by removing the “filters” detail and working on one-depth.

Any help is appreciable. Best regards