In an AngularJS custom filter function, the error message "keys is not defined" is displayed

As I was reviewing examples in an Angular JS book, I came across a concept that has left me puzzled. It involves the use of custom filters with ng-repeat. Below are the code snippets:

<a ng-click="selectCategory()" class="btn btn-block btn-default btn-lg">
    Home
</a>
<a ng-repeat="item in data.products | orderBy: 'category' | unique: 'category'" ng-click="selectCategory(item)" class="btn btn-block btn-default btn-lg">
    {{item}}
</a>

The following snippet shows the controller linked to the HTML body tag.

angular.module("sportsStore").controller("sportsStoreCtrl", function ($scope) {
$scope.data = {
    products: [
        {
            name: "Product #1",
            description: "A product",
            category: "Category #1",
            price: 100
        },
        {
            name: "Product #2",
            description: "A product",
            category: "Category #1",
            price: 100
        },
        {
            name: "Product #3",
            description: "A product",
            category: "Category #2",
            price: 210
        },
        {
            name: "Product #4",
            description: "A product",
            category: "Category #3",
            price: 202
        }
    ]
};

});

The custom filter code is as follows:

angular.module("customFilters", []).filter("unique", function () {
    return function (data, propertyName) {
        if (angular.isArray(data) && angular.isString(propertyName)) {
            var results = [];
            var keys = {};
            for (var i = 0; i < data.length; i++) {
                var val = data[i][propertyName];
                if (angular.isUndefined(keys[val])) {
                    keys[val] = true;
                    results.push(val);
                }
            }
            return results;
        } else {
            return data;
        }
    }
});

The purpose of the custom filter is to generate a list of categories from $scope.data.products.

Although the code works smoothly, my confusion lies in understanding the significance of "var keys = {};" within the custom filter function.

What exactly is the reason behind using the variable "keys" and setting its properties to true?

Answer №1

Filtering through the data in $scope.data based on the "category" property to display unique categories by only showing the first instance of each.

As the loop progresses, it retrieves the value of the "category" key for each data index.

The keys object functions as a record keeper to indicate which values have already been added to the results array.

Assigning a value to the keys object ensures that if the same value is encountered again, it will not meet the condition and will be excluded from the results array.

To illustrate, when processing Product #1, it identifies the category as Category #1, adds it to the results array, and sets key["Category #1"] to true.
Then, with Product #2, upon finding the category value "Category #1", since it's already in the keys object, Product #2 is not included in the results.
Lastly, with Product #3 and its category "Category #2", as this isn't part of the keys object yet, "Category #2" gets appended to the results.

Based on this logic, the expected output would include information for Products #1, #3, and #4.

Removing the line keys[val] = true would result in all products being displayed without filter.

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

Having trouble with implementing ng-hide and ng-show functionality

I have been working on creating my very first Angular website and so far, everything has been going smoothly with the first page. However, I am facing an issue with the second page not appearing as expected when it meets the condition set with ng-show in t ...

Tips for stopping slide transition (moving to a different slide) in vue-slick-carousel?

I'm utilizing vue-slick-carousel to populate schedule data for a specific slide (in this case, a month). <vue-slick-carousel @afterChange="afterChange" @beforeChange="beforeChange" @swipe="swipe" class="te ...

Unspecified locale with Next.js router

Despite extensive research and multiple attempts, I have not been able to find a solution to my problem. That's why I am reaching out for help again. Currently, I am working on a local project and I would like to implement Internationalized Routing f ...

Can you identify the date stored in this JSON object?

I need to analyze some JSON data This is the specific snippet required for my query. "UpdatedDate":"\/Date(1311377875937)\/" I'm unsure about that number, but the updated date indicates when the item was last modified Moreover, how can I ...

JavaScript syntax issue detected, semicolon missing

I've encountered an issue with a form that contains potential errors defined in PHP. To dynamically change the form action based on the presence of errors, I have incorporated JavaScript into the process. The PHP error variable, $errors, has been conv ...

What could be the reason for e.target.value being undefined?

Can someone explain why e.target.value is returning undefined when logged to the console in this simple component? The value should be defined within the element, so I'm confused as to why e.target is not giving the correct value. const NavBar = () = ...

"Using jQuery's animate() function to dynamically change text content

I'm currently venturing into the world of jQuery animate() and decided to create a presentation-style project for practice. However, I've hit a roadblock when attempting to alter the text within my div element in the midst of an animation utilizi ...

Creating unique URLs for websites can be accomplished by following these steps:

I am in the process of developing a website where content in the main div within the body section can be replaced. However, I have realized that all content will end up on the same URL. Any suggestions on how to fix this? HTML/PHP(index.php): <htm ...

What is the functionality of the getBlock('meta') method within DocPad?

While transitioning a website from a different site generator to DocPad, I am currently exploring the capabilities of the getBlock('meta') feature. Understanding how to utilize getBlock('scripts') and getBlock('styles') was re ...

In Javascript, the difference between defining a variable using "this.varName" and "var varName" lies in the scope of the variable

Excuse my JS ignorance, but here's a question: In JS, I've noticed functions that define variables inside them like this: function functionName(){ this.something = ""; }; I'm wondering if something is considered a local variable. W ...

"Troubleshooting Image Loading Issues in Next.js: A Guide to Reloading Unresponsive

Hello, I am facing an issue with rendering 300 images from IPFS data. Occasionally, around 3-4 of the images fail to load and result in a 404 error. Even after refreshing the page, these unloaded images remain inaccessible. It seems like they are permanent ...

How can you determine the number of elements that match in two arrays?

As a coding newbie, I'm looking to create a JavaScript function that compares two arrays and assigns a score based on the number of matching elements. However, when I attempt to run it in Chrome's console, I receive an error message stating that ...

What is the method for reverting style properties back to their CSS defaults using Javascript?

The php-generated page contains multiple elements structured like this: <td class="defaultTDStyle" style="color:userDefinedCustomColor" id="myTDId"></td> There is a default style in place with additional styles ap ...

Ensure that TypeScript compiled files are set to read-only mode

There is a suggestion on GitHub to implement a feature in tsc that would mark compiled files as readonly. However, it has been deemed not feasible and will not be pursued. As someone who tends to accidentally modify compiled files instead of the source fil ...

Add a border to the 'contenteditable' class in a Bootstrap table after it has been modified

Looking for help with JavaScript and jQuery! I have a script that creates an HTML table from a CSV file, using Bootstrap for styling. I want to add CSS or a border to a table cell after it has been edited, but my jQuery attempts haven't worked. Any su ...

Tips for altering promises within nested for loops?

Presented below is a complex function that aims to extract model variants from a csv file, which are stored as strings in an array. The path of this csv file depends on information obtained from other csv files, hence the need for looping. The csvService. ...

What could be causing replace() to malfunction in Node.js?

I am dealing with some data in Node.js and I am trying to replace the ampersands with their escape key. Below is the code snippet I am using: let newValue = data; for (label in labelData.data) { let key = "Label " + label; newValue = newValue.rep ...

Utilizing AngularJS to create a vertical calendar

Looking to create a vertical navigation displaying the date and day for the current week using angularjs. When clicking on the navigation div, I want an alert with the selected date to appear. I attempted this in Plunker using various templates, but was u ...

Checking for an active listening instance of `http.Server` in a Node application

Having an http server and a piece of code that needs to run only when the server is actively listening, I have bound it to the event "listening" as follows : server.on('listening', doSomething) The issue arises when the server is already listen ...

Concealing applicationId and clientToken in Datadog

I'm currently using an Angular application and I've integrated it with the Datadog application to utilize Session and Replay (RUM). However, I am concerned about the security of my sensitive information such as applicationId and clientToken. Is t ...