Array filtering functions similarly to marketplace filtering tools

In order to make the filter function like a marketplace filter, I want to only see items related to the selected brand and status.

For example:

partners = [
0:{
year: "2022"
badge_status: "badge-success"
sale_date: "01/07/2022"
item_sold: "OATMEAL STOUT - Mark The Shadow"
month: "JULY"
partner: "BASTARDS"
quantity_items: 1
status: "COMPLETED" // **true**
amount_paid: 1
},
1:{
year: "2022"
badge_status: "badge-danger"
sale_date: "04/07/2022"
item_sold: "IPA - Hector 5 Rounds"
month: "JULY"
partner: "BASTARDS"
quantity_items: 1
status: "Payment error occurred" // **false**
amount_paid: 4
},
2:{
year: "2022"
badge_status: "badge-success"
sale_date: "04/07/2022"
item_sold: "IPA - Hector 5 Rounds"
month: "JULY"
partner: "BASTARDS"
quantity_items: 3
status: "COMPLETED" // **true**
amount_paid: 3
}
]

This is my current array in the database. I need to be able to filter by 'item_sold' and/or 'status'. Each selected item_sold should return an array as shown in the indexed image below

 this.filtered2 = function(filtering){
      //  console.clear()
      let filterInput = this.search
      let filters = [...this.search].filter(input=> input.value).map(input => ({
        filter: input.name,
        value: input.value
      }))
      console.log('Items to search for', filters)
       return filtrada.filter(product => {
        console.log('PRODUCT', product)
        return filters.every(filter =>{
          console.log("Filter", filter)
          return product[filter.filter] == filter.value
        })
      })

My initial filter will involve selecting the year, month, and partner:

Therefore, in my new array, I will only display products from the selected partner, sale month, and year

The issue arises when I want to apply another filter, to show only the selected products on my list, and if I set a status (sold/not_sold), it should return filtered products with the chosen status. It should function similar to a marketplace array where selecting a brand or price range affects what is displayed...

Currently, following @nem0z's suggestion, when the first item_sold is selected, it returns the filtered array, but upon selecting the second item_sold, it returns empty [].

THIS.SEARCH will receive a value for each selection made on the HTML page

[Image of table only with item_sold filter][1] [1]: https://i.stack.imgur.com/1E9sn.png

Answer №1

Note: You have the freedom to customize the code completely and add or remove filters as needed ;)

Imagine you possess an array of object that represents products, and you want to filter it using html selects with this script:

JS :

    const products = [
    {
        productName: 'product 1',
        partner: 'partner 1',
        status: true,
    },
    {
        productName: 'product 2',
        partner: 'partner 1',
        status: true,
    },
    {
        productName: 'product 1',
        partner: 'partner 2',
        status: false,
    },
];

let filterProducts = function(products) {
    let filterInputs = document.querySelectorAll('.filter');

    let filters = [...filterInputs].filter(input => input.value).map(input => ({filter: input.name, value: input.value}));

    return products.filter(product => {
        return filters.every(filter => {
            return product[filter.filter] == filter.value;
        });
    });
}

document.querySelector('#searchBtn').addEventListener('click', e => {
    let result = filterProducts(products);
    console.log(result);
});

HTML :

    <select name="productName" class="filter">
    <option value="">-----</option>
    <option value="product 1">product 1</option>
    <option value="product 2">product 2</option>
</select>

<select name="partner" class="filter">
    <option value="">-----</option>
    <option value="partner 1">partner 1</option>
    <option value="partner 2">partner 2</option>
</select>

<select name="status" class="filter">
    <option value="">-----</option>
    <option value="1">Yes</option>
    <option value="0">No</option>
</select>

<button type="button" id="searchBtn">Search</button>

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

When navigating to a new URL in Angular 7, the browser will automatically redirect to the home component

Currently, I'm developing a project using Angular 7.2.0. One issue I'm facing is that when I attempt to navigate to a particular page initially, such as: http://localhost:4200/comics?sort=series The browser always gets redirected to the root: ...

Invoke React Component Function using onclick in dangerouslySetInnerHTML

I'm new to React and I have a contenteditable div with dangerouslySetInnerHTML as the child, for formatting user input at runtime. When a specific span is clicked inside the HTML, I want to update a variable in the parent component using setState. Is ...

change visibility:hidden to visible in a css class using JavaScript

I've put together a list of Game of Thrones characters who might meet their demise (no spoilers included). However, I'm struggling with removing a CSS class as part of my task. Simply deleting the CSS is not the solution I am looking for. I' ...

What is the best way to output multiple Div elements using Jquery or Javascript?

I have the following HTML code snippet: <div id="box"> <div id="id_1></div> <div id="id_2></div> <div id="id_3></div> <div id="id_4></div> </div> Can someone guide me on how to use Jquery or ...

Exploring solutions for handling asynchronous issues with vue3-google-map

While working with a Vue library for managing Maps called vue3-google-map, I encountered an issue when trying to define certain polylines that would not allow me to select the center of the marked area: Here is my map template: <template> <Goo ...

Can someone guide me on configuring Material-UI DataGrid in React to have multiple headers with column span?

Is there a way to achieve multiple headers with column span in the Material-UI DataGrid component? view image example ...

Stop users from repeating an action

We are encountering challenges with users repeating a specific action, even though we have measures in place to prevent it. Here is an overview of our current approach: Client side: The button becomes disabled after one click. Server side: We use a key h ...

Error code 70006 encountered in Typescript when attempting to reference a type as "any"

Currently, I am working on a React project that involves using TypeScript. This is quite new to me, and I have encountered a type error in one of my components... let dragStart = (e) => { let transferringData = e.dataTransfer.setData("text", e.tar ...

Angular doesn't support this particular type as an injection token

I'm attempting to create a constructor with a type of string, but I keep encountering the following error: This particular type is not supported as an injection token @Injectable({providedIn: 'root'}) export class DataService { const ...

Execute the 'loadURL' function in the electron-Angular project when the Angular Compiler has finished preparing

When working with electron-Angular tutorials, it is common to create the window and load index.html from localhost after a set timeout. You'll often come across instructions similar to this: // set timeout to render the window not until the Angular c ...

Building a Multifaceted Website using React and Node.js

I've encountered a rather straightforward issue. My goal is to incorporate a second checkout page into my React and Node Website. I initially believed that the solution would be as simple as adding another 'checkout' Route to the Browser Ro ...

JavaScript Filtering Techniques

Looking for a simpler way to remove an item from a list of 10 items without using arrow functions. My current method is shown below, but I'm seeking a more efficient solution. function getFilteredItems(myItems) { var items = ['item1& ...

My NPM Install is throwing multiple errors (error number 1). What steps can be taken to troubleshoot and

I'm encountering an issue with my Angular project while trying to run npm install from the package.json file. Here are some details: Node version - 12.13.0 Angular CLI - 7.2.4 gyp ERR! configure error gyp ERR! stack Error: unable to verify the fi ...

When calling mongoose.connect(), the initial parameter must be a String but it was found to be

I am facing issues while setting up the test database for testing purposes. The connection error shown when trying to connect to MongoDB using Mongoose is: throw new MongooseError('The `uri` parameter to `openUri()` must be a ' + ^ MongooseEr ...

Express-Session Object Method

I am currently facing an issue with linking an object to an Express session. Below is the code I am using: var express = require('express'); var session = require('express-session'); // Defining an object named "engine" which simulate ...

Minimize the cyclomatic complexity of a TypeScript function

I have a typescript function that needs to be refactored to reduce the cyclometric complexity. I am considering implementing an inverted if statement as a solution, but it doesn't seem to make much of a difference. updateSort(s: Sort) { if (s.ac ...

The persistentFilter in the Tabulator is failing to verify for the headerFilterEmptyCheck

Using Tabulator version 4.4.3 When filtering the checkbox in the usual way, everything works fine. If I set a filtered checkbox to true on a column, it functions correctly: headerFilterEmptyCheck: function (value) { return !value; }, Howev ...

Tips for correctly linking JS and CSS resources in Node.js/Express

I have a JavaScript file and a stylesheet that I am trying to link in order to use a cipher website that I created. Here is my File Path: website/ (contains app.js/html files and package json) website/public/css (contains CSS files) website/public/scri ...

What could be the reason behind receiving a TypeError upon refreshing the page, where it claims that a state is not found even though that may not be the actual situation?

Within my application, I have a component called Wall. Users are redirected to the Wall component after successfully logging in from the Login component. In the Wall component, I am retrieving and displaying the user's name that they used during regis ...

Executing a function with the initial click

Is there a way to run a function only on the first click, without having it run every time? I already have another function running on window.onload, so I can't use that. Both functions work fine independently, but not together. Right now, I'm ca ...