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

Utilizing a combination of Mongo, Mongoose, Multer, and FS for deleting images

Looking at the code snippet below:- var Image = mongoose.model("Image", imageSchema); //Assuming all the configuration of packages are done app.delete("/element/:id", function(req, res) { Image.findByIdAndRemove(req.params.id, function(err) { if(e ...

Ways to display a GIF image as a pop-up during data loading in an MVC application

I am working on a project using the MVC framework. The application retrieves a large amount of data during loading. I would like to display a loading image - a .gif file while fetching records. Below is the code snippet I am currently using: //Loads rec ...

Matching a regular expression pattern at the beginning of a line for grouping strings

One of my tasks involves working with a markdown string that looks like this: var str = " # Title here Some body of text ## A subtitle ##There may be no space after the title hashtags Another body of text with a Twitter #hashtag in it"; My goal ...

Enable express to disregard specific URL modifications

I'm currently working on creating a Single Page App using Express. One of the challenges I am facing is that the Express route feature forces the view to be re-rendered every time the URL changes and a GET request is sent to the server. My code typica ...

Guide on toggling the visibility of two child components using *ngif in Angular 4 without losing the data

Is there a way to preserve data in my child component while using *ngIf to show and hide? I am unable to utilize the [hidden] attribute. <div id="parentcomponent"> <child1 *ngif="child1"></child1> <child2 *ngif="child2"></chi ...

Exploring the process of introducing a new property to an existing type using d.ts in Typescript

Within my src/router.ts file, I have the following code: export function resetRouter() { router.matcher = createRouter().matcher // Property 'matcher' does not exist on type 'VueRouter'. Did you mean 'match'? } In an ...

Prepending a string to the value using Angular's ngOptions

I've been working on creating a custom directive for Angular that includes a label and select element with necessary classes. This is what my directive code looks like: return { restrict: 'E', scope: { text: &a ...

Sending a Thunk to the store using Typescript

Within my primary store.ts file, the following code is present: const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); Upon initial rendering, an action is dispatched to fetchUser in ord ...

Using Angular to pass a class as a parameter in an HTTP GET request

I am currently working with a class that looks like this: export class CodeTable { public tableId: number; public connectionTable: number; public connectionCode: number; public code: number; ...

JavaScript is displaying Not a Number (NaN) instead of the expected value

Currently, I am facing an issue with retrieving the user's work duration from a database column stored in minutes. My goal is to convert this value to HH:mm format to calculate the total hours worked per week, but I'm encountering obstacles. < ...

Fuzzy text in drop-down box on Chrome, clear on Firefox

I've encountered an issue with a dropdown menu in Google Chrome where the content appears blurry, while it displays correctly in Firefox. The problem arises when the dropdown exceeds a certain height, and I've tried setting a max-height with over ...

backbone.js router failing to recognize URL fragments

I have set up a basic router in my code and initialized it. Issue: I encountered an unexpected behavior when visiting the URL http://localhost/backbone1/#photos/5. Despite expecting an output from console.log() in the JavaScript console, nothing appears. ...

Utilize the angularJS filter to emphasize the search text within the search results

I have a search box that filters results displayed on the screen. I am using a filter called 'startWith' for this purpose. Now, I need to implement a feature where the search text is highlighted among the search results in angularJS. For example ...

AJAX issue: "Content-Type header is missing the multipart boundary parameter"

Currently, I am encountering an issue while attempting to transfer a file from localhost to a server. The error message displayed in my network console is as follows, with status code 500: "no multipart boundary param in Content-Type" To address this p ...

What is a callback function tied to a specific URL?

I need to implement a functionality in my web application where users can click on a link within a datatable, which will then load a new table on a separate page. This new table should only display rows that have the same id as the row that was clicked on ...

Utilizing TypeScript to export a class constructor as a named function

Imagine you have this custom class: export class PerformActionClass<TEntity> { constructor(entity: TEntity) { } } You can use it in your code like this: new PerformActionClass<Person>(myPersonObject); However, you may want a more co ...

What is the process for NPM to execute a command that is not located in the path directory?

When I try to run the ava command from my project directory that contains AVA tests, I encounter an issue because it is not in my path. In my project, the npm test command is configured as ava tests/*.js --verbose, and mysteriously manages to execute the ...

What is the alternative to the deprecated 'combineLatest' method in rxJs and how can it be replaced?

Recently, I came across a situation where I had implemented a method using the combinlatest rsjx/operator. It was working perfectly fine. However, Sonar flagged it as deprecated and now I need to update it to the latest version. When I tried to simply re ...

Issue with the Styled Components Color Picker display

For the past 6 months, I have been using VSCode with React and Styled Components without any issues. However, recently I encountered a problem where the color picker would not show up when using CSS properties related to color. Usually, a quick reload or r ...

Tips for locating the previous CSS value before it was altered by javascript code

I am working on adjusting the CSS variables provided by the system using JavaScript with the following code: document.body.style.setProperty("--rh__primary-base", "rgba(254,80,0)"); However, when I inspect the element, I can see that t ...