How can I merge my two custom filters into a single, more efficient custom filter?

I have developed two custom filters that are quite similar. The only distinction between these filters is the array they utilize. Therefore, I am considering creating a single custom filter and passing an array as a parameter to it. The arrays I intend to pass into the function are $rootScope.selectedCategories and $rootScope.selectedBrands. However, my dilemma lies in determining where to declare a variable that can be used as an argument for the filter, as demonstrated below.

<div class="productContentBox" ng-repeat="top in store.tops | categoryFilter: argument1 | orderBy: propertyName">

I attempted to create a scope variable in my controller with the following code structure. My approach was to use 'categoryArray' as the argument for the categoryFilter (thus replacing 'argument1' with 'categoryArray' in the previous code snippet). Unfortunately, this strategy did not yield the desired outcome, as I suspect the variable does not update according to the current $rootScope.selectedCategories (which is subject to change based on checkbox selections).

$scope.categoryArray = $rootScope.selectedCategories;

Below is the coding for the initial filter:

// Filter that operates based on product categories.
app.filter('categoryFilter', ['$rootScope', function($rootScope) {
    return function(items) {
        // Display all products if no filters are selected.
        if ($rootScope.selectedCategories.length == 0 || checkOnlyFalse($rootScope.selectedCategories)) {
            return items;
        } else {
            var filtered = [];
            for (var i=0; i < items.length; i++) {
                var item = items[i];
                // Add products matching the filter criteria to the array.
                for (var j=0; j < $rootScope.selectedCategories.length; j++)
                    if (item.category == $rootScope.selectedCategories[j]) {
                        filtered.push(item);
                    }
            }
            return filtered;
        }
    };
}]);

And here is the coding for the second filter:

// Filter that operates based on product brands.
app.filter('brandFilter', ['$rootScope', function($rootScope) {
    return function(items) {
        // Display all products if no filters are selected.
        if ($rootScope.selectedBrands.length == 0 || checkOnlyFalse($rootScope.selectedBrands)) {
            return items;
        } else {
            var filtered = [];
            for (var i=0; i < items.length; i++) {
                var item = items[i];
                // Add products matching the filter criteria to the array.
                for (var j=0; j < $rootScope.selectedBrands.length; j++)
                    if (item.brand == $rootScope.selectedBrands[j]) {
                        filtered.push(item);
                    }
            }
            return filtered;
        }
    };
}]);

Answer â„–1

Check out this straightforward solution

app.filter('productFilter', ['$rootScope', function($rootScope) {
  return function(items,filterOn) {
    var filtered = [];
    // Display all products if no filters are selected.
    if('categories'===filterOn) {
      if ($rootScope.selectedCategories.length == 0 || checkOnlyFalse($rootScope.selectedCategories))  {
        filtered=items;
      } else {
        for(var i=0; i < items.length; i++) {
          var item = items[i];
          // Add the products that match the filter criteria to the array.
          for (var j=0; j < $rootScope.selectedCategories.length; j++) {
            if (item.category == $rootScope.selectedCategories[j]){
              filtered.push(item);
            }
          }
        }
      }
    } else if('brands'===filterOn) {
      // Display all products if no filters are selected.
      if ($rootScope.selectedBrands.length == 0 || checkOnlyFalse($rootScope.selectedBrands))  {
        filtered=items;
      } else {
        var filtered = [];
        for(var i=0; i < items.length; i++) {
          var item = items[i];
          // Add the products that match the filter criteria to the array.
          for (var j=0; j < $rootScope.selectedBrands.length; j++)  {
            if (item.brand == $rootScope.selectedBrands[j]){
              filtered.push(item);
            }
          }
        }
      }
    }
    return filtered;
  };
}]);

You can utilize this in your html like so

<div class="productContentBox" ng-repeat="top in (store.tops | product: 'categories') | orderBy: category">

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

JavaScript events for scrolling horizontally and vertically across multiple browsers

Is there a way to capture mousewheel and touchpad events, including on Mac, using JavaScript? Ideally, I want to get deltaX and deltaY values for both horizontal and vertical movements. I came across a website - - that appears to handle touchpad events ho ...

Using Angular directives with Kendo UI Grid to create a foreign key column

I'm currently working on building a Kendo Grid that incorporates 2 foreign key columns using the Angular directives for Kendo. The challenge I am facing is that while one column works perfectly fine, the other does not (each works independently of the ...

Utilize local JSON file to display images on a webpage using AngularJS

Where am I making a mistake? I am trying to display images from a datahl.json file on my web page, but for some reason, I am unable to access them. Please review the code snippets below and help me out. If possible, provide a solution using Plunker edito ...

Learn the process of playing a video in an HTML5 video player after it has finished downloading

// HTML video tag <video id="myVideo" width="320" height="176" preload="auto" controls> <source src="/server/o//content/test2.mp4" onerror="alert('video not found')" type="video/mp4"> Your browser does not support HTML5 vid ...

Retrieve the string data from a .txt document

I am facing an issue with my script that retrieves a value from a .txt file. It works perfectly fine when the value is a number, but when trying to fetch text from another .txt file, I encounter the "NaN" error indicating it's not a number. How can I ...

Is there a way to use Jquery to determine if a parent div contains a scroll

I'm trying to find a jQuery example that checks if any parent div has a scroll bar, but I can't seem to locate a helpful one. Here is the code snippet I am working with: <div> <div class="heading"> <div class="visit ...

Transferring information through AJAX and fetching through PHP

Below is my current AJAX code setup: optionScope.data().stage = 'b'; $.ajax({ url: "functions/contact.php", type: "post", data: {'stage': optionScope.data().stage}, success: function(data, status) { ...

Triggering an event when the cursor enters a specific div/span/a element and again when the cursor exits the element

Here's the scenario - Imagine a contenteditable element with text inside. I'm working on creating a tagging feature similar to Twitter's mention tagging when someone types '@'. As the user types, a popover appears with suggestion ...

Can a website built on Express.js be optimized for SEO?

Would pages created with the traditional route structure provided by Express (e.g. ) appear on Google's Search Engine Results Page as they would for a Wordpress blog or PHP website using a similar path structure? ...

Is it possible to execute a function within an HTML page simply by clicking on it?

As someone who is new to the world of HTML, CSS, and JS, I'm currently facing a challenge: On my website's page1.html, I have implemented a feature that allows users to sort different articles on the page by selecting a sub-menu from the navigat ...

What causes the "node: bad option" error to occur when I include a custom flag in the nodejs command line within an Angular 9 application?

Seeking assistance with adding a custom flag to the npm start command in an Angular 9 project. The goal is to intercept proxy requests within the local server and manipulate data. However, encountering the "node: bad option" error consistently. Looking for ...

Simulating a traditional table scroll function on a window using virtualization

I am currently attempting to incorporate a virtualized table in react using react–virtualized, but I am facing issues with the rendering of the table. I am seeking to understand the root cause for this problem as well as find solutions for other overlapp ...

Error in Winston: Unable to determine the length of undefined property

I encountered an issue with my Winston Transport in the express backend of my MERN app. The error message reads: error: uncaughtException: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefi ...

Using different CSS classes interchangeably in AngularJS

Imagine you have a list with an unknown number of items, ranging from one to potentially dozens. You want to display five CSS classes in a regular alternating pattern. What would be the most effective approach to achieve this? Here is some sample HTML cod ...

Steps to create a new window using Raphael JS

Is there a way to create a new window in Raphael similar to using "_blank"? ...

Utilize a callback function without any arguments, and make use of the

After working on tutorials from nodeschool.io, I encountered a challenging problem related to streams. The provided solution had me puzzled. I'm particularly confused about the role of the upper variable and why it's necessary to use this.push. ...

I must add and display a tab for permissions

I am currently using the material UI tab for my project. My goal is to display the tab only when the permission is set to true. I have successfully achieved this functionality, but the issue arises when the permission is false. It results in an error that ...

execute field function prior to sorting

Currently, I am building a graphql server in express and using a resolver to modify my fields based on user input from the query. The issue arises from the transformer function returning a function. My goal is to sort the results by a field determined by ...

The encoding error in the encoding process must adhere to valid encoding standards

I recently developed a basic program that utilizes process.stdin and process.stdout. However, when I executed the program and tried to input a value for stdout, an error message popped up stating "TypeError: 'encoding' must be a valid string enco ...

Leveraging Environment Variables in Separate JavaScript Files within a Node Express Application

After trying various methods and searching extensively online, I am struggling to use environment variables in a separate JavaScript file within an Express App. My Setup: In my Express app, I have an index.js file that serves an HTML page with associated ...