Filter a data array using a two-dimensional filter array that may change dynamically

Currently, I am facing a challenge where I need to filter a data array of objects using a two-dimensional filter array of objects.

Here is a glimpse of my data array:

dataArray = [{
    Filter_GroupSize: "1"
    Filter_Time: "5-30"
    title: "Tools Test 1"
}, {
    Filter_GroupSize: "5-10"
    Filter_Time: "60-120"
    title: "Tools test 2"
}, {
    Filter_GroupSize: "5-10"
    Filter_Time: "120-240"
    title: "Tools 3"
}, {
    Filter_GroupSize: "10-20"
    Filter_Time: "240-360"
    title: "Tools Test 4"
}]

The complexity arises from the fact that the two-dimensional filter array can vary in size over time. In this illustration, it consists of 2 arrays, but it can expand or contract. As the filter array changes, so does the data array.

Below is the current structure of my two-dimensional filter array of objects:

FiltersToApply = [
    [{
        choice: "5-10"
        internalColName: "Filter_GroupSize"
    }, {
        choice: "10-20"
        internalColName: "Filter_GroupSize"
    }],
    [{
        choice: "60-120"
        internalColName: "Filter_Time"
    }, {
        choice: "120-240"
        internalColName: "Filter_Time"
    }]
]

My goal is to filter the data array and only retrieve elements that match both the "Filter_GroupSize" and "Filter_Time" values from the 2D filter array. For example, given the current filter array, I would like to collect the "Tools test 2" and "Tools 3" elements into a new array. The filter function should scan "FiltersToApply[0]" for a match, then check "FiltersToApply[1]" for a consistent match on the same dataArray element.

I have made progress with the following code snippet:

            for (let i = 0; i < FiltersToApply.length; i++) {
                console.log(FiltersToApply[i]);
                FiltersToApply[i].forEach((filter) => {
                    var filteredArray: Tool[] = dataArray.filter((item) => {
                        if (item[filter.internalColName] == filter.choice && ((i+1) <= FiltersToApply.length)) {
                            this.nextArray(FiltersToApply[i+1], item);
                        }
                    });
                });
            }

However, I am currently at a roadblock. Any suggestions or solutions would be greatly appreciated!

Answer №1

I managed to make it work using the snippet below. Essentially, I flattened the filter array, grouped the choices by property names, and then filtered the data based on those groups.

var data = [{
    Size: "1",
    Time: "5-30",
    name: "Test 1"
}, {
    Size: "5-10",
    Time: "60-120",
    name: "Test 2"
}, {
    Size: "5-10",
    Time: "120-240",
    name: "Test 3"
}, {
    Size: "10-20",
    Time: "240-360",
    name: "Test 4"
}];

var Filters = [
    [{
        choice: "5-10",
        prop: "Size"
    }, {
        choice: "10-20",
        prop: "Size"
    }],
    [{
        choice: "60-120",
        prop: "Time"
    }, {
        choice: "120-240",
        prop: "Time"
    }]
];

var filterData = Filters.flat().reduce(function (a, cv) {
    (a[cv.prop] = a[cv.prop] || []).push(cv.choice);
    return a;
}, []);

var result = data.filter(function(v){
    return filterData.Size.indexOf(v.Size) > -1 && filterData.Time.indexOf(v.Time) > -1
});

console.log(result.map(function(v){ return v.name; }))

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

Deleting database information using Jquery when a div is clicked

I'm looking to create an alert system where users will see a pop-up alert on their screen. However, I am facing a major issue in removing the div completely. I understand that I need to remove it from the database, but I'm struggling with finding ...

What is the best approach to merging multiple arrays to create a new array in CodeIgniter?

Here are two arrays provided below, where I want to combine the first key of the first array with the second key of the second array to create a new array. [animals1] => Array ( [0] => Horse [1] => Dog1 ...

HTTP provider is missing! Error: No HTTP provider found! encountered injectionError at this juncture

Encountered an error: No provider for Http! Error: No provider for Http! at injectionError Sample Component File: import { Component,Injectable } from '@angular/core'; import { HttpModule, Http } from '@angular/http'; import { IonicPa ...

Encountered a SyntaxError in vue + webpack regarding an invalid range in character class

I am currently using webpack 4.29.3 and vue.js 2.6.3 to create a simple hello world project. I expected the index.html file to render correctly, but I encountered an error: SyntaxError: invalid range in character class. This error is confusing because I&ap ...

Is it possible to customize the information displayed in a Mat-Dialog based on the object being

My current project involves the presentation of various boxes on a screen. Each box contains a button that, when clicked, redirects to another page. Here is the interface for the box object: export interface Allbox { image: string, link: string, ...

Creating interactive and adaptable maps

Currently, I am working on making a Joomla website responsive. However, I have encountered an issue with the SobiPro Map. The problem arises when displaying a map (background img) and points (a link + img) over it with an absolute position. As a result, wh ...

``Where can I find information on setting a timeout for a node.js application

Is it feasible to implement a timeout for running node.js? I am faced with the issue of connecting to external services that occasionally do not respond, causing my script to hang and the node.js process to freeze. I am seeking a solution to enforce the t ...

Convert a multidimensional array into a standard array

I am dealing with an array structure that looks like this Array ( [0] => Array ( [text] => 1 ) [1] => Array ( [0] => Array ( [text] => 2 ) ...

Encountering a null pointer exception when launching the Chrome browser using Selenium

Hope you all are doing well. I need assistance in resolving a null pointer issue while developing a new Selenium framework for my company. The problem arises after calling the method "StartBrowser()" from the base class in the browser class. Everything ru ...

Dealing with router parameters of an indefinite number in Angular 5: A comprehensive guide

Is there a method to efficiently handle an unknown number of router parameters in a recursive manner? For instance: We are dealing with product categories that may have subcategories, which can have their own subcategories and so on. There are a few key ...

Using ExtJS to populate a panel with data from various sources

I am currently working with an Ext.grid.GridPanel that is connected to a Ext.data.JsonStore for data and Ext.grid.ColumnModel for grid specifications. Out of the 10 columns in my grid, 9 are being populated by the json store without any issues. However, I ...

View the picture in a web browser

Currently, I am faced with the challenge of displaying an image that is stored in an MSSQL database created by another person. The column was originally of type IMAGE, but I converted it to varbinary(MAX) using Sequelize. Although I lost some data during ...

Is there a way to replicate Twitter's "what's happening" box on our website?

Currently, I am trying to extract the cursor position from a content-editable box. However, when a new tag is created, the cursor appears before the tag instead of after it. Additionally, I am having trouble with merging/splitting the tags. Any suggestions ...

Using useEffect in React with an empty dependency array is a

The issue: I'm facing a challenge with managing the timer in my code. If I remove the dependency array from the useEffect, the timer keeps running endlessly. On the other hand, when I include a dependency array in the useEffect, the timer gets stuck a ...

Eliminating null values from a multidimensional array

Is there a way to remove the array elements cctype, cctypologycode, and amount if they are empty? What would be the most efficient approach? { "ccInput": [ { "designSummaryId": 6, "CCType": "A", "CCTypologyCode": "A", "Amount ...

Locate the div element containing specific text and remove the text from the

Is there a way to locate a div that contains specific text and remove only that specific text from the div? For instance: <div> DeleteText <span>Something text</span> <div>Something span inner text </div> </div> I am l ...

Managing an unexpected variable when making an AJAX request

Here is a code snippet that I am working with: var User = { get: function (options) { var self = this; $.ajax({ url: options.url, success: function (data, response) { self.nextPageUrl = data.pagination.next_page; opt ...

Achieve automated zooming out using highcharts-ng through code

Currently, I am using Highcharts-ng as seen on https://github.com/pablojim/highcharts-ng Upon inspecting the source code, I have noticed some interesting functionalities in the directive utilizing scope.$on which I can leverage for broadcasting. One examp ...

What is the best way to incorporate data types into a React useReducer reducer function?

I originally had a useReducer function in pure react without TypeScript, but now I want to add types to it. Here is the useReducer reducer function in pure react without types: export const cartReducer = (state, action) => { switch (action.type) { ...

Top recommendation for creating a customizable grid in Angular

We are currently in the process of transitioning our application from GWT to angular. Within our application, we have implemented an editable grid feature. One method for making the grid editable is to use a separate editor for each cell. However, this ap ...