Filtering in AngularJS can be performed by checking if a value in a specific key of one array is also present as a value in a specific

This query was originally posted on this thread

I am looking to implement a filter that will display the values of colors.name only if they also exist in cars.color

$scope.colors = [{"name":"blue","count":2},
                 {"name":"red","count":12},
                 {"name":"pink","count":5},
                 {"name":"yellow","count":2}];

$scope.cars=[ {"brand":"Ford","color":"blue", "seat":"pink"}
       ,{"brand":"Ferrari","color":"red", "seat":"pink"}
       ,{"brand":"Rolls","color":"blue","seat":"pink"}];

When displaying in the view:

<ul>
    <li ng-repeat="n in colors | filter: filteredColors"> {{n}}
    </li>
</ul>

The expected outcome is:

  • blue
  • red
  • I am seeking a solution without using ES6, and I prefer to have the filter logic within the controller. Visit the following plunkr here. Thank you in advance!

    Answer №1

    code snippet:

    var app = angular.module('myApp', []);
    
    app.controller('DataCtrl', function($scope) {
    
      $scope.items = [{"name":"apple","quantity":5},
                     {"name":"banana","quantity":10},
                     {"name":"orange","quantity":7},
                     {"name":"grape","quantity":3}];
    
      $scope.filters=[ {"type":"fruit","color":"red"}
           ,{"type":"vegetable","color":"green"}
           ,{"type":"fruit","color":"yellow"}];
    
      $scope.filteredItems = function(filter) {
        var itemsArray = $scope.filters;
        for(var i = 0; i < itemsArray.length; i++) {
          if (filter.name === itemsArray[i].type) {
            return true;
          }
        }
        return false; 
      };
    
    });
    

    webpage structure:

    <!DOCTYPE html>
    <html ng-app="myApp">
    
      <head>
        <meta charset="utf-8" />
        <title>AngularJS Example</title>
        <link rel="stylesheet" href="styles.css" />
        <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="70114e47554c414307494750042403">[email protected]</a>" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js" data-semver="1.8.2"></script>
        <script src="script.js"></script>
      </head>
    
      <body ng-controller="DataCtrl">
        <ul>
            <li ng-repeat="item in items | filter: filteredItems"> {{item.name}}
            </li>
        </ul>
      </body>
    
    </html>
    

    Answer №2

    If you want to customize your filtering process, you can create a custom filter like this:

    app.filter('colorFilter', function(){
        return function(val){
            var colorsList = [{"name":"blue","count":2},
                 {"name":"red","count":12},
                 {"name":"pink","count":5},
                 {"name":"yellow","count":2}];
            var filteredColors = []
            angular.forEach(val, function(item){
                angular.forEach(colorsList, function(color){
                    if(item.color === color.name)
                        filteredColors.push(item)
                })
            })
            return filteredColors;
        }
    })
    

    After creating the filter, you can use it in your HTML like this:

    <li ng-repeat="car in cars | colorFilter"> {{car.color}}
    

    Give this approach a try and see how it works for you.

    Answer №3

    In response to your initial inquiry, there are solutions available that do not utilize ES6. AngularJS - How to check that a specific key has a specific value in an array

    It seems unnecessary to rely on built-in functions for your logic.

    Consider using a manual loop instead of resorting to map or include, keeping it simple and following traditional JavaScript practices within angularjs. Refer to this answer as guidance, and implement it with angular.filter().

    var app = angular.module("myApp",[]);
    app.controller("myCtrl",function($scope){
    $scope.colors  = [{"name":"blue","count":2},
                 {"name":"red","count":12},
                 {"name":"pink","count":5},
                 {"name":"yellow","count":2}];
    
    
    
    $scope.cars=[ {"brand":"Ford","color":"blue"}
               ,{"brand":"Ferrari","color":"red"}
               ,{"brand":"Rolls","color":"blue"}];
    
    $scope.filteredColors = function () {
    var colorsvar = $scope.colors;
    var carsvar = $scope.cars;
    $scope.newValue = [];
    for (var i = 0; i < colorsvar.length; i++) {
        for (var j = 0; j < carsvar.length; j++) {
            if (colorsvar[i].name == carsvar[j].color) {
                if ($scope.newValue.indexOf(colorsvar[i].name) ==-1) {
                    $scope.newValue.push(colorsvar[i].name);
                }
            }
        }
    }
       return $scope.newValue;
      };
     })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    
    <div ng-app="myApp" ng-controller="myCtrl">
    <ul>
        <li ng-repeat="n in filteredColors()"> {{n}}
        </li>
    </ul>
    </div>

    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 date formatting without using jQuery

    Looking for help to apply a date mask (dd/mm/yyyy) on an ASP.net textbox. I have tried several JavaScript solutions found through Google search, but none seem to work seamlessly, especially with backspacing. Any suggestions for a reliable script would be ...

    What is the best way to configure my AngularJS routing for managing URL rewriting and page reloads effectively?

    As I develop my website using AngularJS, one of my main goals is to create a smooth navigation experience without the annoying "browser flash" effect that occurs when switching between pages. This means that clicking on a link in index.html to go to foo.ht ...

    Having difficulty adding items to the shopping cart

    While working on a simple checkout system using django and react, I encountered an issue. Upon clicking the add to cart button, instead of adding the item to the cart as intended, I receive a 404 page not found error. I suspect that the problem may lie in ...

    How can I showcase the selected file using jQuery's querySelector?

    I have successfully implemented a file upload feature using jQuery querySelector. Now, I am looking for a way to display the selected file name in a span element after the user selects the file. Here is my HTML code: <span id="filename"></span&g ...

    Conflicts arising between smoothState.js and other plugins

    After successfully implementing the smoothState.js plugin on my website, I encountered an issue with another simple jQuery plugin. The plugin begins with: $(document).ready() Unfortunately, this plugin does not work unless I refresh the page. I have gone ...

    How can constants in AngularJS be defined in relation to other constants?

    I've been attempting to set constants using other constants, but it seems that this cannot be achieved due to the initial constant not being ready when the dependent constant requires it. I am curious to know if this is indeed an impossible task. My ...

    Learn the steps for submitting and interpreting information in Node Express

    I am attempting to send this JSON data to a node express endpoint { "data": [ [ "Audit Territory", "LA Antelope Valley", "LA Central", "LA East San Gabriel", "LA San Fernando Valley", "LA West", ...

    The parameter 'data' is assumed to have an 'any' type in React hooks, according to ts(7006)

    It's perplexing to me how the 7006 error underlines "data," while in the test environment on the main page of React Hooks (https://react-hook-form.com/get-started#Quickstart), everything works perfectly. I'm wondering if I need to include anothe ...

    Is it no longer possible to create custom linked Context Menus in Tabulator 5?

    After using Tabulator for a few years, we have decided to switch over to Angular v13 and upgrade to the new Tabulator 5.x. In our previous implementation, we had set up a custom ContextMenu in the Table Column Definition like this: contextMenu: this.TableR ...

    What is the process for opening and populating dialogs from dynamically mapped cards?

    I have a unique array of JSON data that is connected to Material-UI (MUI) cards. Each card features a button that triggers a dialog to open. When clicking the button on a card, I aim to pass the specific value of GroupName into the dialog. In my case, ther ...

    What is the best way to change the "MuiPaper-elevation1" attribute in a Card element within Material-UI?

    My Card component in HTML looks like this: <div class="MuiPaper-root MuiCard-root makeStyles-Card-5 MuiPaper-elevation1 MuiPaper-rounded"> I want to change MuiPaper-elevation1 to MuiPaper-elevation0 to remove the shadow. I attempted: ...

    Having trouble with d3 / svg layering when introducing new nodes overtime

    Struggling with a frustrating issue on my d3 force directed map project. Initially, I render the necessary nodes and links, then periodically check for updates through AJAX. The problem arises when adding new nodes and links – they appear over existing c ...

    What is the best way to show only a specific v-for element in Vue.js?

    Is there a way to select a specific item from a v-for loop in vue js? I am using v-for to retrieve Youtube data API items. Each item contains an iframe that should only be displayed when a user clicks on a play button. Currently, all the iframes are shown ...

    Utilizing NextJS to retrieve cookie data within React components

    Currently, I am working with a Next.js frontend and an Express backend. For authentication, I am utilizing cookies and have set up protected routes using Next.js middleware. The next step in my project involves accessing the cookie response within React ...

    Moving an array in AngularJS from one file to another

    As someone new to AngularJS, I am facing an issue with integrating two separate files that contain modules. Each file works fine individually - allowing me to perform operations on arrays of names. However, when switching views, the arrays remain stored un ...

    Ways to break down a collection of multiple arrays

    Looking to transform an array that consists of multiple arrays into a format suitable for an external API. For example: [ [44.5,43.2,45.1] , [42, 41.2, 48.1] ] transforming into [ [44.5,42], [43.2,41.2] , [45.1, 48.1] ] My current code attempts this ...

    What is the best way to input an HTML element into AngularJS code?

    I am looking to integrate the html element into my angularjs code. Within my HTML, I have elements such as data-form-selector='#linechart_general_form' and data-url="{% url 'horizon:admin:metering:samples'%}" that I need to access withi ...

    Comparison of Ajax and submit: Why am I not receiving identical responses?

    Utilizing Ajax for submission and all global variables ending in box. Note that the initialization code is functioning correctly. function begin() { if (confirm("Proceed at your own risk as all consequences are yours!!")) { var usernameNa ...

    Can you provide an example and explain the functions `getOptionSelected` and `getOptionLabel` in Material UI?

    While going through the Mui Documentation, I came across the Autocomplete component section and found two interesting props: getOptionLabel and getOptionSelected. Although I read their definitions, I'm still struggling to grasp them fully. Can someone ...

    Learn the technique of looping through multiple HTML elements and wrapping them in Vue.js easily!

    i need to wrap 2 HTML elements together Here is my code snippet using Vue.js <tr> <th v-for="(item9,index) in product_all" :key="item9.id"><center>Qty</center></th> <th v-for="(item99,index) in product_all" :key=" ...