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

Exploring the functionality of arrays in Jest's cli option --testPathIgnorePatterns

Looking to exclude multiple folders, one in the src folder and another in node_modules, when using the --testPathIgnorePatterns option. Does anyone have an example of how to use this pattern effectively? I am unable to configure an array in the package.js ...

Struggling to update the state of an array using ReactJS and unsure of how to iterate through it

Currently, I am in the process of developing a movie voting application for me and my friends using React. I have made significant progress but I am facing issues with setting or updating the state of the 'rating' object. The structure of the ar ...

Use Jquery to select the checkbox inside the td element and mark it as

I've created an HTML table with checkboxes in the td elements, like so: <table id="my_table"> <tr> <td><input type="checkbox" name="td1"></td> <td><input type="checkbox" name="td2"></td> </ ...

I'm feeling a bit lost with this API call. Trying to figure out how to calculate the time difference between the

Currently, I am working on a project for one of my courses that requires making multiple API calls consecutively. Although I have successfully made the first call and set up the second one, I find myself puzzled by the specifics of what the API is requesti ...

Removing duplicate entries from a dropdown menu can be achieved by implementing

As a newcomer to the world of PHP PDO, I've learned that the database connection should be in a separate PHP file. However, after spending an entire day trying different things, I'm still facing issues. I suspect that the duplicate entries are a ...

A guide on transferring documents between collections using Mongoose and MongoDB

I have a list of tasks that includes both completed and incomplete items. Additionally, I have two buttons - one for deleting an item (which is functional) and the other for marking an item as done or not. I am struggling with creating a function to move ...

Identifying modifications to the content of a text area

Is there a way to determine if the value in my textareaId has changed due to JavaScript? For example: $("#buttonID").on("click, function(){ $("#textareaID").val("lorem ipsum"); }); $("#textareaID").change(function(){ //not working }); $ ...

transferring information between two ajax calls upon completion of the first ajax request

Attempting to pass data to jvectormap from an ajax call, using a when function to ensure the code runs after the ajax call has finished loading. The issue I'm facing is that the map appears empty and I encounter an error. Uncaught ReferenceError: ...

I encountered difficulty in assigning a JSON response to a variable, both with and without using JSON.parse()

I'm in the process of creating a website that, among other things (and crucially for this particular issue), stores your current location data in a variable by fetching it from the ipinfo API (https://ipinfo.io/json) After encountering the problem of ...

Storing data collected from a Google form into an Excel spreadsheet

I have created a form using table layout. My goal is to automatically shift the focus to the next input field once the current one reaches its maximum length. I tried implementing this functionality with jQuery, but it only seems to work with inputs and no ...

Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated. The current representation of individual's data ne ...

The function 'compilation.emitAsset' is not recognized by the sitemap-webpack-plugin

I'm currently working on setting up a sitemap for my live environment and I've encountered an issue while trying to utilize the sitemap-webpack-plugin. The error message I received is as follows: ERROR in TypeError: compilation.emitAsset is not a ...

What does the curly braces {} signify in the JavaScript programming language

While delving into sample code, I came across a line that left me puzzled. var foo = {}; From my observations, it seems like this is being used as a type of array where the index is a string provided by the user instead of traditional numerical indexes. ...

Encountered a problem when incorporating delay functions into redux-saga testing using the Redux Saga Test Plan library

I am facing a challenge while trying to test my redux-saga functions using the Redux Saga Test Plan library. The issue arises due to delay functions present in my saga. All tests pass smoothly without any errors when I remove the line containing yield del ...

A lone function making two separate calls using AJAX

I have a function that includes two Ajax Get calls. Each call has a different function for handling success. function get_power_mgt_settings() { window.mv.do_ajax_call('GET',power_mgt.get_spin_down_url{},'xml',true,show ...

Guide to customizing the Autocomplete jQuery plugin to mimic Google's result replacement feature

I have implemented the jQuery plugin Autocomplete like Google for two form fields - foo and bar (which is dependent on the value of foo): $(function() { $("#foo").autocomplete({ minLength: 3, limit: 5, source : [{ u ...

A JavaScript regex that can identify white spaces and new lines to calculate word count

Currently, I am attempting to count words within the Summernote editor using Angular. While I have successfully created a service for counting words, it seems to be ineffective when encountering new lines. Here is an example of the text: Hult Internation ...

What is the best way to utilize XMLHttpRequest for sending POST requests to multiple pages simultaneously?

I have a unique challenge where I need to send data to multiple PHP pages on different servers simultaneously. My logic for sending the post is ready, but now it needs to be executed across various server destinations. var bInfo = JSON.stringify(busines ...

The Bootstrap 5 navigation bar does not extend to the full width of its parent

While working on a Bootstrap navigation inside a container, I encountered an issue where the navigation bar was not expanding to match the width of the container. It seemed like the padding had to be manually adjusted to fit properly. Below is the code sn ...

I'm having trouble getting rid of this stubborn loader on the website

I am currently utilizing the following template: . My objective is to eliminate the preloader progress bar that displays the loading progress of the page in percentage. The files associated with this preloader are as follows: Loader CSS File - www[dot]the ...