Using JavaScript to Filter Through Numerous Values Based on Different Attributes

My goal is to efficiently filter multiple attributes with multiple values

'arr' represents a list of all products, and 'f_...' indicates the attribute such as color or type.

'namet' denotes the selected attribute by the user.

'keyt' contains the values associated with each attribute like red, yellow, and green.

 let arr = [
        { "id": 523, "f_105": ["992","996"],  "f_104": ["985"], "f_106":["1000"] },
        { "id": 524, "f_105": ["993","996"],  "f_104": ["984"], "f_106":["1001"] }
    ]

The arrays selected by the user for searching purposes

To extract the attributes, following code can be used:

var namet = ['f_106', 'f_106', 'f_105', 'f_105', 'f_104'];
var keyt  = ['1000' , '1001', '993', '996', '985'];

Alternatively,

var chosenKey = ['f_106', 'f_105', 'f_104']
var chosenAttr = {
    "f_106": ["1000", "1001"],
    "f_105": ["993", "996"],
    "f_104": ["985"],
}

Or,

var chosenAttr =
[
    {"f_106": ["1000", "1001"]},
    {"f_105": ["993", "996"]},
    {"f_104": ["985"]}
]

I am looking for a method that iterates through the data to generate results similar to variable 'filtered'

var filtered = d => 
        (d.f_106.indexOf("1000") > -1 || d.f_106.indexOf("1001") > -1) && 
        (d.f_105.indexOf("993")  > -1  || d.f_105.indexOf("996") > -1)  &&
        (d.f_104.indexOf("985")  > -1)

Then apply the filtering process like this:

const f = arr.filter(filtered);

An alternative approach could involve applying a different method to filter products based on multiple attributes.

Answer №1

Upon reviewing the sample I provided, I am confident that it will address the issue you are facing.

let data = [
    { "id": 523, "f_105": ["992", "996"], "f_104": ["985"], "f_106": ["1000"] },
    { "id": 524, "f_105": ["993", "996"], "f_104": ["984"], "f_106": ["1001"] }
]


var selectedData =
    [
        { "f_106": ["1000", "1001"] },
        { "f_105": ["992"] },
        { "f_104": ["985"] }
    ]



function filterData() {
    var copiedArr = data;

    for (i = 0; i < selectedData.length; i++) {
        for (var key in selectedData[i]) {
            copiedArr = copiedArr.filter(function (item) {
                var match = false;

                for (var idx in selectedData[i][key]) {
                    let value = selectedData[i][key][idx];

                    if (item[key].indexOf(value) > -1) {
                        match = true;
                    }
                }
                return match;
            });
        }
    }

    return copiedArr;
}

var filteredResults = filterData();
$('#result').html(JSON.stringify(filteredResults));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre>
<code id="result">
  
</code>
</pre>

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

A practical method for restructuring or dividing a string containing JSON entries

Within my dataset, I've got a string comprising JSON entries linked together similar to the following scenario. val docs = """ {"name": "Bilbo Baggins", "age": 50}{"name": "Gandalf", "age": 1000}{"name": "Thorin", "age": 195}{"name": "Balin", "age" ...

How to implement datepicker on multiple input fields

Below are the two input fields that have datepicker functionality: <div class="row"> <input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="dt" is-open="opened" min="minDate" max="'2015-06-22&apos ...

Uh oh! An error occurred while trying to create the ngFileUpload module

After using NuGet to install Angular File Upload 12.2.13, I made sure to inject the dependencies correctly. However, despite this, I keep encountering the following error: angular.js:63 Uncaught Error: [$injector:modulerr] Failed to instantiate module c ...

Invoking a function means calling another one simultaneously

There are two buttons in my code: The button on the right triggers a function called update(): <script> function update(buttonid){ document.getElementById(buttonid).disabled = true; event.stopPropagation(); var textboxid = buttonid.sli ...

Error: 'callback is not a function' when using function.apply()

Why is this not working as expected? The error message indicates that typeof(callback) is undefined. function A(a, callback) { document.write(typeof(callback)); callback(); return a; } function Run(func, args) { return func.apply ...

Troubleshooting issues with cross-domain jQuery ajax requests

Struggling with this code and unable to make it work. This call consistently returns a "Failed to load resource: the server responded with a status of 401 (Unauthorized)" error message. $('#btnZendesk').click(function () { $.ajax({ ...

How to use Javascript to set focus on a dropdown list within a PHP script

Having trouble setting focus on the dropdown list in my PHP page dc-test.php, where there are two dropdown lists that are interdependent. The values for these dropdown lists are fetched from a database table. I am unable to set focus on the first dropdown ...

Strategies for smoothly navigating the page to a specific div every time

Currently, I am working on a form that requires submitting multiple child forms. To enhance user experience, I have incorporated jQuery functionality to display a message at the top of the page upon each submission. Now, my goal is to implement a feature w ...

Guide to accessing an element in a two-dimensional Python array

I am attempting to modify the value of a specific element in a 2D array. This array is a matrix with dimensions num1 by num2, where every element is initially set to 0. My goal is to change the value at the Rth row and Cth column of the matrix to 1. matri ...

Controlling the file selection window of a browser with protractor/jasmine

The tools I am currently using are Protractor 3.3.0, Jasmine 2.4.1, and Selenium Standalone Server. My main objective is to create a test scenario where the test navigates to a specific page and then clicks on an 'upload file' button. This actio ...

A guide on transferring a Vue component to a custom local library

After successfully creating components using template syntax (*vue files), I decided to move common components to a library. The component from the library (common/src/component/VButton): <template> <button ... </button> </templat ...

Using React with TypeScript to ensure that at least one key of a type is not null, even if all keys are optional

Within my Typescript code, I have defined an event type that includes various time parameters: export type EventRecord = { name: string; eta: string | null; assumed_time: string | null; indicated_time: string | null; }; I also have a func ...

Alerts for drop down menu validation with multiple buttons

My goal is to design a multi-step form that collects user information. This form consists of 5 stages: Step 1: User details (Name, email, phone, age, gender) Step 2: Yes or No question Step 3: Yes or No question Step 4: Yes or No question Step 5: Yes o ...

Using target="_blank" does not seem to open a popup window in React

The issue is that the target="_blank" attribute is not working properly for the modal popup window. Instead, the link is opening in the same page and the popup is closing. <TermLink to="/legal/privacy-policy" target="_blank"> Privacy Pol ...

Employing ng-repeat within a ui-scope

I'm having trouble getting my ui-view to update dynamically using ng-repeat. I'm not sure if what I want to do is even possible because when I add static objects to intro.html, they display properly. Thank you for any assistance, JS }).st ...

Ensuring the accurate promise is delivered in Angular

I'm struggling to correctly return the promise for a service in Angular. Here is the function causing me trouble: postToSP.post($scope.sharePointURL, data).then(function() { $scope.gettingData = false; $scope.yammerListName = ...

`How can I eliminate all duplicate entries from an array of objects in Angular?`

arr = new Array(); arr.push({place:"1",name:"true"}); arr.push({place:"1",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"3",name:"false"}); arr.push({place:"3",name:"true"}); I'm curious about ...

Sending Paypal IPN Data to Node.JS: A Step-by-Step Guide

I'm looking to implement a real-time donation system on my website that can update all users simultaneously. The challenge I'm facing is that the IPN (Instant Payment Notification) page, responsible for verifying payments, is written in PHP. Unf ...

Attempting to modify the background hue of a grid component when a click event is triggered

I am struggling with the syntax to change the color of an element in my grid when clicked. I have attempted different variations without success. Being new to JavaScript, I would appreciate some gentle guidance if the solution is obvious. JS const gri ...

Issue with DropdownListFor validation using jQuery when the onchange event triggers submission

DropdownListFor @Html.DropDownListFor(x => x.selectedDateFilter, new SelectList(Model.bydatefilter, "id", "dt", Model.selectedDateFilter), "--Select Date--", new { onchange = @"this.f ...