applying various conditions to JavaScript arrays for filtering

After spending countless hours trying to solve my filtering issue, I'm still struggling. I'm in the middle of creating a react marketplace where users need to be able to apply multiple filters on one page. Here's an example of my product list:

productsList = [{brand: 'Zara', category: 'Jeans', color: 'blue'}, {brand: 'BlaBla',color: 'blue', category: 'Leggins'}, {brand: 'Louis', category: 'Leggins', color: 'red'}, {brand: 'Louis', category: 'Jeans', color: 'pink'}]

In my state, I have an object containing various filter options:

filters: {
  designers: ['Zara', 'Louis'],
  categories: [],
  colors: ['pink']
}

If I only want to display Zara jeans that are blue, how can I effectively filter out the results? I've tried using lodash and other methods found online but haven't been successful yet. Any guidance would be greatly appreciated!

Answer №1

To adapt the keys of filters to match the objects, consider creating a separate object to act as a translation between them.

Transform the filters into entries ([key, value]) and remove any empty entries (where the array is empty). Utilize Array.filter() to loop through the productList, checking if the current object's property is included for all existing entries.

const applyFilters = (filters, arr) => {
  const entries = Object.entries(filters)
    .filter(([, v]) => v.length)
  
  return arr.filter(o => 
    entries
      .every(([k, v]) => v.includes(o[k]))
  )
}

const productsList = [{brand: 'Zara', category: 'Jeans', color: 'blue'}, {brand: 'BlaBla',color: 'blue', category: 'Leggins'}, {brand: 'Louis', category: 'Leggins', color: 'red'}, {brand: 'Louis', category: 'Jeans', color: 'pink'}]

const filters = {
  brand: ['Zara', 'Louis'],
  category: [],
  color: ['pink']
}

const result = applyFilters(filters, productsList)

console.log(result)

Follow the same approach but with your original filter names and mapping them to object properties:

const filtersToProps = {
  designers: 'brand',
  categories: 'category',
  colors: 'color'
};

const applyFilters = (filters, arr) => {
  const entries = Object.entries(filters)
    .filter(([, v]) => v.length)
    .map(([k, v]) => [filtersToProps[k], v])
  
  return arr.filter(o => 
    entries
      .every(([k, v]) => v.includes(o[k]))
  )
}

const productsList = [{brand: 'Zara', category: 'Jeans', color: 'blue'}, {brand: 'BlaBla',color: 'blue', category: 'Leggins'}, {brand: 'Louis', category: 'Leggins', color: 'red'}, {brand: 'Louis', category: 'Jeans', color: 'pink'}]

const filters = {
  designers: ['Zara', 'Louis'],
  categories: [],
  colors: ['pink']
}

const result = applyFilters(filters, productsList)

console.log(result)

Answer №2

const filteredProducts = productsList.filter(product => {
    return Object.keys(filters).every(key => {
        if (!filters[key].length) return true;
        switch (key) {
            case 'designers':
                return filters[key].includes(product.brand);
            case 'categories':
                return filters[key].includes(product.category);
            case 'colors':
                return filters[key].includes(product.color);
        }
    })
})

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

UI-Router: What is the best way to access a page within my project without adding it as a State?

Currently in the process of learning Angular and UI-Router. Initially, I followed the advice of many and chose to utilize UI-Router. In my original setup, the login page was included in all States. However, I decided it would be best to keep it as a separ ...

Determining special characters within a string using VueJS

As a newcomer to VueJS, I am currently developing an application that requires a signup and login system. My goal is to inform the user if they have entered a special character such as /[&^$*_+~.()\'\"!\-:@]/. In order to achieve th ...

Comparing Express.js View Engine to Manual Compilation

Currently, I am utilizing Express.js along with the hbs library to incorporate Handlebars templates in my application. Lately, I've delved into establishing a build system using gulp for my app and stumbled upon packages like gulp-handlebars. My query ...

Explore various queries and paths within MongoDB Atlas Search

I am currently working on developing an API that can return search results based on multiple parameters. So far, I have been able to successfully query one parameter. For example, here is a sample URL: http://localhost:3000/api/search?term=javascript& ...

Assurance of retrieving information

I am looking to extract specific information from the following website . I have implemented Promises in order to retrieve data about planets, then films associated with a particular planet object. My next goal is to access data within the species array ne ...

The radio input is not being properly checked using ng-checked in Angular

The ng-checked attribute is causing issues in the application, specifically with radio buttons. It seems to be working fine for checkboxes but not for radio buttons. <input type="radio" class="radio" name="job_class_radio" ng-checked="key===jobClassDat ...

Unable to generate this QUIZ (JavaScript, HTML)

Hi there, I'm working on a sample quiz and having trouble displaying the result. As a coding newbie, I could really use some help. In this quiz, users answer questions and based on their responses, I want to display whether they are conservative, agg ...

Using JavaScript to create a dynamic to-do list that persists on the browser even when refreshed

I created a Javascript Todolist that is functioning well, but I am seeking a way to ensure that my Todo-items persist on the browser even after refreshing until I choose to delete them. Any suggestions or advice on how I can achieve this? ...

Switch between GeoJSON layers by using an HTML button within Mapbox GL JS, instead of relying on traditional links

I am currently developing a web map that requires toggling two GeoJSON layers on and off. In the past, I used Mapbox JS to accomplish this task by adding and removing layers with a custom HTML button click. However, I am facing some challenges in achieving ...

Navigating the changes of daylight savings time requires proper management

I am seeking a solution to manage daylight saving time using momentjs. When receiving a datetime value (such as 2022-04-05T10:59:13.640683) from the backend in a front-end application, I need to determine if I am in DST in order to display the correct date ...

Add a click event to elements that match

I must admit that I am not particularly knowledgeable in Javascript/jQuery and my question might come across as trivial. However, I am trying to assign a click event to every element on the page with the following code: $(document).ready(function () { ...

How can I implement API redirection in my Node.js application?

Currently, I am working on a mock authentication system in Node.js using passport and JWT. I have successfully created an API and I am using handlebars for templating. My dilemma arises when a user tries to login by sending their credentials to the API. I ...

The destruction of scope is not activated

Check out my issue in action with this plunkr demo. The problem I'm encountering is quite straightforward: manually calling $destroy or removing the element does not trigger the $destroy event. function link(scope, element, attrs) { // Manually ca ...

Leverage the variable from one function in a different function within Three.js using Javascript

After loading an obj file using three.js, I attempted to obtain the 'X' position of its vertices and save it in a variable named 'pos' inside the objloader function within the init() function. My goal was to access this variable's ...

Use jQuery to detect the presence of the class .class, and if it exists, automatically append the same class to a specific #id element on a particular webpage

Need help with jQuery - adding a specific class to an element based on the presence of another class Hello everyone, I have searched through various forums and tried multiple code snippets in JavaScript and jQuery to no avail. Despite other scripts worki ...

Troubleshooting: Unable to get the Bootstrap active navigation code to function

I've been struggling to make this code work in order to add the active class to my navigation list item, but it just won't cooperate. Home <li id="orange"> <a href="hotels.php"><span class="glyphicon glyphico ...

Guide to integrating the Google identity services library in a React application

I've encountered an issue with my current code, which has suddenly stopped working: import React, { Component } from "react"; import Auth from "../../helper/auth"; import PropTypes from "prop-types"; import logo from &quo ...

The JavaScript code for summing two numbers is not functioning as expected

My HTML code takes a user input number, performs a calculation using a formula, and displays the output. The chosen input is inserted into the formula, and the result is added to the original number. However, there seems to be an issue with adding decimal ...

Utilize jQuery to convert text to lowercase before adding Capitalize CSS styling

I have encountered a situation where I need to change the HTML link values from UPPERCASE to LOWERCASE and then apply a capitalization style. The problem lies in the fact that the links arrive in uppercase, so I had to come up with a workaround: The given ...

Updating view with *ngIf won't reflect change in property caused by route change

My custom select bar has a feature where products-header__select expands the list when clicked. To achieve this, I created the property expanded to track its current state. Using *ngIf, I toggle its visibility. The functionality works as expected when cli ...