Filter an array of objects using criteria from a separate array [TypeScript/JavaScript]

I am faced with a scenario where I have two dropdowns, each designed to filter specific keys of an object. The key feature here is that the dropdown selections should not depend on each other; in other words, filtering can occur independently based on the values chosen from either dropdown.

https://i.sstatic.net/w0y7j.png

Upon selecting an option from a dropdown, I receive an array containing two objects corresponding to each dropdown:

[
    {
        "name": "Type",
        "value": [
            "calibration"
        ],
        "selected": [
            {
                "text": "calibration"
            }
        ]
    },
    {
        "name": "Function group",
        "value": [
            "1 - Test",
            "2 - Programming"
        ],
        "selected": [
            {
                "text": "1 - Test"
            }
        ]
    }
]

The above displays two distinct objects, one for each dropdown - "Type" and "Function group".

In these objects, the "value" represents all options available in the corresponding dropdowns while the "selected" field holds the chosen item driving the filtering process. In this case, we have opted for "calibration" and "Test".

The "Type" dropdown filters based on the data's "category" field, whereas the "Function group" dropdown operates on the "groupDescription" field. The dataset targeted for filtering using these specified keys and selected values appears as follows:

const mockData = [
      {
        operationDetails: {
          id: '5119-03-03-05',
          number: '41126-3',
          description: 'Clutch wear, check. VCADS Pro operation',
          category: 'calibration',  //type dropdown
          languageCode: 'en',
          countryCode: 'GB'
        },
        functionDetails: {
          groupId: 411,
          groupDescription: 'Test', //function group dropdown
          languageCode: '',
          countryCode: ''
        },
        lastPerformed: '2021-02-22',
        time: 20,
        isFavorite: false
      }
      ,
      {
        operationDetails: {
          id: '5229-03-03-05',
          number: '41126-3',
          description: 'Defective brake pad',
          category: 'calibration',  ///type dropdown
          languageCode: 'en',
          countryCode: 'GB'
        },
        functionDetails: {
          groupId: 411,
          groupDescription: 'Programming',  //function group dropdown
          languageCode: '',
          countryCode: ''
        },
        lastPerformed: '2020-01-22',
        time: 20,
        isFavorite: false
      }
    ]

Access the playground with mock data and sample response from dropdown here.

What approach should be taken to effectively filter the data based on the values provided by the dropdown objects and their respective keys?

Answer №1

Although it may not be the most aesthetically pleasing code, it certainly gets the job done. The key point to keep an eye on here is the regex usage. It would be more efficient to avoid parsing and opt for a direct match like category, but if your scenarios are fixed, you should be able to determine whether this approach will work reliably every time. Additionally, having a field key in filterDetails would be helpful so that you can identify which field needs to be matched in the actual data and incorporate that logic.

const filterDetails = [
  {
    name: "Type",
    value: ["calibration"],
    selected: [
      {
        text: "calibration",
      },
    ],
  },
  {
    name: "Function group",
    value: ["1 - Test", "2 - Programming"],
    selected: [
      {
        text: "Test",
      },
    ],
  },
];

const mockData = [
  {
    operationDetails: {
      id: "5119-03-03-05",
      number: "41126-3",
      description: "Clutch wear, check. VCADS Pro operation",
      category: "calibration", //type
      languageCode: "en",
      countryCode: "GB",
    },
    functionDetails: {
      groupId: 411,
      groupDescription: "Test", //function group
      languageCode: "",
      countryCode: "",
    },
    lastPerformed: "2021-02-22",
    time: 20,
    isFavorite: false,
  },
  {
    operationDetails: {
      id: "5229-03-03-05",
      number: "41126-3",
      description: "Defective brake pad",
      category: "calibration", ///type
      languageCode: "en",
      countryCode: "GB",
    },
    functionDetails: {
      groupId: 411,
      groupDescription: "Programming", //function group
      languageCode: "",
      countryCode: "",
    },
    lastPerformed: "2020-01-22",
    time: 20,
    isFavorite: false,
  },
];

console.log(
  "filtered mockData: ",
  mockData.filter(({ operationDetails, functionDetails }) => {
    let groupDescriptionMatch = false;
    let categoryMatch = false;
    for (const details of filterDetails) {
      if (
        details.name === "Type" &&
        details.selected[0].text === operationDetails.category
      )
        categoryMatch = true;

      if (details.name === "Function group") {
        let parsedGroup = details.selected[0].text.match(/[a-zA-Z]+/g);
        if (parsedGroup[0] === functionDetails.groupDescription) {
          groupDescriptionMatch = true;
        }
      }
    }
    return groupDescriptionMatch && categoryMatch;
  })
);

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

Retrieve all direct message channels in Discord using DiscordJS

I need to retrieve all communication channels and messages sent by a bot. The goal is to access all available channels, including direct message (DM) channels. However, the current method seems to only fetch guild channels. client.channels.cache.entries() ...

Selenium EventFiringWebDriver JavaScript: There is a SyntaxError due to a missing closing parenthesis after an argument in

Attempting to run a javaScript command through the EventFiringWebDriver class in Selenium. EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(driver); eventFiringWebDriver.executeScript("document.querySelector('[ng-reflect-title=&ap ...

Mixed Protocol Error (HTTP/HTTPS)

I'm experiencing a mixed content error on my website, as it is using both http and https protocols. Chrome console displays the following error: Mixed Content: The page at '' was loaded over HTTPS, but requested an insecure XMLHttpReques ...

What is the location within an object3d where I can access the dynamic point coordinates?

Watching one singular point rotate around the Y axis is quite intriguing. I am eager to witness the shift in X coordinate as it moves along its trajectory. Although the starting point remains unchanged, I wonder where the dynamic coordinates lie. Cou ...

Error message: "Ajax script is failing to run"

Currently I am delving into the world of Ajax and have encountered a minor issue. I've been attempting to make a POST request to a Django backend using ajax, but strangely enough, the alert isn't showing up on screen. Furthermore, upon inspectio ...

The file socket.io.js could not be located

I've encountered an issue with my node server where it is unable to serve the route /socket.io/socket.io.js as I consistently receive a 404 error. I have attempted compiling different versions of node (currently using 0.6.13 which works on another s ...

Exploring how to successfully test the parsing of a string using JSON.parse in Jest

Currently, I am in the process of creating unit tests for an API. In a scenario where I implement the following code: const apiResponse:object = JSON.parse(body) expect(apiResponse).toHaveProperty('error') If the API does not return JSON data, ...

Oops! Looks like something went wrong. The command to install the debug app failed because the emulator could not be launched. This could be due to the fact that no emulators were found

I'm in need of assistance to resolve these issues Encountered an error while trying to install the app. Please ensure that your Android development environment is properly configured: https://reactnative.dev/docs/environment-setup. Error: Command fai ...

Tips for concealing .js and .map files in WebStorm during your work on an Angular 2 TypeScript project

After attempting to include the extensions in the .gitignore file, the outcome is shown in the following image: https://i.sstatic.net/0K6x5.png Unfortunately, the files are still not fully concealed. ...

Tips on maintaining and storing values for every loop and filling HTML rows correspondingly

Our task is to store the value of each iteration and then load these values into corresponding HTML rows. The server will provide dynamic responses: (based on the key selected by the user) Key:"Apple" values:0:Array[2] 1:"500" 1: Array[2]0:""1:"765" "Key: ...

Issue with discord.js - Unable to stop MessageCollector

Is it possible to stop the collector if a time limit of 1 millisecond is set? const filter = message => message.author.id === message.author.id; const receiver = new MessageReceiver(message.channel, filter, { max: 3, time: 1000, }) receiver. ...

Trouble getting proper alignment displayed with JavaScript and CSS

If anyone has a solution for printing content in a div using JavaScript and CSS, please help. The main div with the id 'preview' contains content taken from a database using PHP and MySQL. However, the data on the print page appears vertically an ...

use ajax to dynamically append a dropdown menu

Currently working on creating a form that includes a dropdown menu populated with elements from a database. The challenge I'm facing is ensuring that once an element is selected from the dropdown, another one appears dynamically. My goal is to use AJA ...

Seeking assistance with troubleshooting JavaScript code for counting vowels

I am currently trying to debug a piece of code for my class. I have made several adjustments, but for some reason it is still not functioning correctly. The goal is to count the number of vowels in a given phrase and display them in the div element. Howeve ...

Is it possible for me to use AJAX to load content from a string? I am attempting to postpone the activation of certain HTML

I need help optimizing my HTML page that includes certain sections with large Javascript files and images, which are initially hidden. Even when set to "display: none," the browser still loads all the content. One solution could be moving those sections in ...

Collaborative spreadsheet feature within a browser-based software platform

I am using an Angular-based SPA for my web application. My goal is to be able to open an Excel file within the application itself. Currently, I have a menu button or link that is linked to a specific path, for example //192.168.10.10/sharedExcels/myExcel. ...

Strategies for breaking apart a large, monolithic Node.js JavaScript application

My node.js server application is expanding, and I am looking to split it into multiple files. Below is a snippet of the current monolithic server.js file: var express = require('express'); var app = express(); // other initialization code etc / ...

Struggling with setting up eslint in my typescript project

Below is the contents of my package.json file: { "devDependencies": { "@typescript-eslint/eslint-plugin": "^5.13.0", "@typescript-eslint/parser": "^5.13.0", "airbnb": "^0.0.2&qu ...

Building unique queries using TypeScript and React testing-library

I am currently working on creating a custom query specifically for Testing Library in TypeScript to be used with a React project. The custom query is designed to retrieve the first th cells within the tbody of the container: // all-table-headings.ts - cust ...

Creating dynamic class properties in NestJs Swagger API definitions

I am working with the following code snippet: export class DocumentsSteps { @ApiProperty({type: ???}) [type: string]: DocumentStep; } Can anyone help me determine how to define the type for ApiProperty? ...