How can I efficiently filter my array or JSON data in JavaScript using multiple criteria, including handling multi values?

One of the challenges posed here is:

  • Some values include more than one item (like active substances: ["Morphine", "Fentanyl"])
  • Some values repeat themselves (retrospective: "1" for "true"; ward_focused: "1" for true (again))

Unfortunately, the previous solutions I attempted did not suit my project.

jsonData

[
 {
  "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"
  }
 }
]

query

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

The approach that came close to providing a solution involved converting the data into an array and manipulating it as follows:

  const filterArr = Object.values(selectedFilters).flat();

  const output = myDataArray.filter(({filters}) => {
      const objFilters = Object.values(filters).flat();
      return filterArr.every(val => objFilters.includes(val));
  })
  console.log(output);

However, this method failed due to the repetitive occurrences of "1" for "true" and "2" for false in each profile.

I am willing to work with both JSON and array for my data. I may also consider modifying the "1" -"2" structure for my boolean data types. If necessary, the data structure can be altered by removing the “filters” detail and working on a single level.

Any assistance provided would be greatly appreciated. Best regards

Answer №1

Utilize the code snippet below to efficiently filter your data by employing the JavaScript filter function and comparing each potential filter with the filters object.

const 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"
  }
 }
];
function filterJson(filterObj) {
  let hasRetrospective = false,
    hasWardFocused = false,
    hasIndicationFocused = false,
    hasActiveSubstance = false;
  const arr = json.filter(function (j) {
    hasRetrospective = filterObj.retrospective.indexOf(j.filters.retrospective) > -1;
    hasWardFocused = filterObj.ward_focused.indexOf(j.filters.ward_focused) > -1;
    hasIndicationFocused = filterObj.indication_focused.indexOf(j.filters.indication_focused) > -1;
    hasActiveSubstance = Array.isArray(j.filters.active_substance) ?    
      j.filters.active_substance.some(function (jf) {
        return filterObj.active_substance.indexOf(jf) > -1;
      }):
      filterObj.active_substance.indexOf(j.filters.active_substance) > -1;
    return hasRetrospective && hasWardFocused && hasIndicationFocused && hasActiveSubstance;
  }); 
  console.log(arr);
}
filterJson({
    retrospective: ["1"],
    ward_focused: ["1"],
    indication_focused: ["1"],
    active_substance: ["Morphine", "Fentanyl"]
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger a jQuery modal by clicking on a cell within a table

As a novice in jquery, I am facing a challenge. I have a table with a column showing the total number of employees in a department. When a user clicks on this column, it should open up a jquery modal displaying a list of employees like EmpA, EmpB, and Em ...

Exploring JSON with JavaScript

[ {"lastName":"Noyce","gender":"Male","patientID":19389,"firstName":"Scott","age":"53Y,"}, {"lastName":"noyce724","gender":"Male","patientID":24607,"firstName":"rita","age":"0Y,"} ] The data above represents a JSON object. var searchBarInput = TextInput. ...

Are there any options available for customizing the animation settings on the UI-bootstrap's carousel feature?

If you're interested in seeing an example of the standard configuration, check out this link. It's surprising how scarce the documentation is for many of the features that the UIB team has developed... I'm curious if anyone here has experie ...

The issue with IE-9 is that it is mistakenly picking up the placeholder value as

My HTML code looks like this: <input id="SLOCriteriaOtherText" name="SLOCriteriaOtherText" style="width: 100%;" type="text" data-role="autocomplete" placeholder="Enter name for 'other' metric..." class="k-input" autocomplete="off" role="textb ...

Enhancing User Interactions: A Guide to Sorting and Generating Multiple Text Fields using jQuery UI's Droppable

Scenario: I am looking to allow my users to create a shopping list by dragging products into a sortable and droppable list. Depending on the position of the product on the list and its value, the text fields in the form should be automatically filled. Try ...

Saving Information to a Specific Location on the Client Side in a CSV File

I am currently working on a static application that uses Angular JS technology. My goal is to write data into a CSV file at a specific path in order for another API to read the data from that location. Despite searching extensively on the internet, I hav ...

Navigating through an optional object in Swift 4 using loops

I'm facing an issue with the following code snippet: let dic = snapshot.value as! [String:[String:Any]] Array(dic.values).forEach { print($0["fcmToken"]) } The output shows three tokens: Optional(c1DdtdDF1Rs:APA91bGJBUD65nidQiFDO90AVNgq0wiMjUaZ ...

When a div tag containing PHP is empty, it should either be hidden or show specific text based on your requirements

Among the plethora of unanswered queries regarding hiding empty divs, I find myself unable to make any of the suggested solutions work. Hence, I am putting forth my own question. On my webpage, there is a specific section dedicated to showcasing various it ...

The appearance and cleanliness of Three.js 3D models leaves much to be desired

Currently, I am working on 3D Modeling with Three.js and I am facing an issue in displaying a clean and neat product after reading a .DAE file. Despite adding light sources, my product display is not up to the mark. Here is the actual product that should b ...

Is implementing an API necessary for handling this basic event in Express JS?

Lately, I've been encountering challenges with the backend, particularly when working with Express JS. I realize that part of the problem might be my own misunderstanding - assuming that Express JS is a framework generator for MVC or solely for authen ...

While working on a JSON project in Xcode, I encountered an error in the first part of my sample

I encountered the error below: Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x6a2b1a0 {NSLocalizedDescription=Unrecognised leading character} Could you kindly explain the meaning of this error ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

Dealing with Asynchronous Frustrations: Is it best to utilize callbacks and what is the most effective way to pass them across various

I am working on developing a straightforward text-based game that functions within a socket.io chat room on a node server. The structure of the program is as follows: At present, there are three key modules: Rogue: serves as the core of rogue game functi ...

Error in tabs.onUpdated argument in Firefox WebExtensions

I am currently working on developing a straightforward webExtension for Firefox and I would like to implement tabs.onUpdated with a filter. I found an example on the Mozilla website that I decided to use: const pattern1 = "https://developer.mozilla.org/*" ...

Removing multiple data rows in JSP using AJAX by selecting check boxes

I have a requirement where I need to store a list of objects (each with a unique id) as a session parameter. These objects are then displayed in a table in a JSP using JSTL. <c:forEach var="list" items="${PlayerList}"> <tr> <td> ...

NestJS Logger: Issue setting logger types in main.ts

When attempting to specify logger types in main.ts as illustrated in the official documentation: const app = await NestFactory.create(ApplicationModule, { logger: ['error', 'warn'], }); await app.listen(3000); I am encountering an i ...

Dynamic list choices determined by prior selections

As someone new to Wordpress, I am working on a car platform theme but facing some challenges with the car-selling functionalities. One specific issue is the need to show or hide options based on previous selections made with dropdown lists. For instance, ...

Analyzing length of strings by dividing content within div tags using their unique ids

Here's my issue: I'm using AJAX to fetch a price, but the source from where it is fetched doesn't add a zero at the end of the price if it ends in zero. For example, if the price is 0.40 cents, it comes back as 0.4. Now, my objective is to t ...

When transmitting data from the parent component to the child component, the data successfully passes through, yet the view fails to reflect the

I'm facing an issue with passing data from a parent component to a child component using props. Here is the code snippet I'm working with: <div id="root"> <my-component v-bind:account-types='accountTypes'> </my-c ...

Differences in Print Layout Between Chrome and Firefox when Viewing a PHP Website

I have been working on creating a print command to print a specific div, and I have managed to successfully run the print command using default methods like CTRL + P and also with a button click. The Issue: However, I have encountered a problem where the ...