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

Implementing access restrictions for modules in NodeJS

In Node, is it possible to limit access or permit access only to specific modules from a particular module? Should I consider replacing the require function and object in the global scope for this purpose? I have concerns about the security of a certain mo ...

AngularJS view fails to reflect updates in the model

This issue with Angular has been widely discussed online, but I ask for your patience. I have tried various solutions without success. Here is a simplified version of my code: View: <div ng-hide="{{beHidden}}"></div> Controller: // Set beHi ...

Unable to post form data into database due to Javascript undefined data situation

I've been working on an HTML form that can interact with a PHP API to retrieve client data and then update user stats in a MySQL database. Currently, I am converting the data into a JSON object and using JSON.stringify to create a string for sending ...

The challenge with our unique PHP/JS Analytics Solution

Here's an illustration of the code snippet for Google Analytics: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'userIDhere']); _gaq.push(['_trackPageview']); _gaq.push([&apos ...

Exploring Node.js with the power of EcmaScript through Javascript Mapping

I am currently using Map in NodeJS version 0.10.36 with the harmony flag enabled. While I am able to create a map, set and retrieve data successfully, I am facing issues with other methods such as size, keys(), entries(), and forEach as they are returning ...

Tips on inserting text into form input fields

I need some guidance on how to enhance my form input functionality. The form currently consists of an input box and a submit button. When the user clicks submit, the form content is submitted and processed using javascript. What I am aiming for is to autom ...

Utilizing class references within a method

I have been developing a script that is designed to dynamically load content into multiple predefined DIVs located in the topbar section of my website. Within the Topbar Object, there is an object called Ribbon which contains functions for manipulating on ...

Animate jQuery Images - Transform and smoothly reveal element

Hey there! I've managed to create a color switcher that gives a sneak peek of different themes. Currently, it simply switches the image source and loads the new image. But I'm curious if it's possible to add a fadeIn effect to enhance the t ...

New methods for Sequelize ES6 models do not currently exist

Encountering issues while using Sequelize JS v4 with ES6 classes, I'm facing difficulty with the execution of instance methods. Despite being defined in the code, these methods appear to be non-existent. For instance - Model File 'use strict&a ...

The function crypto.randomUUID() does not exist in the Vitest library

vite.config.ts import { sveltekit } from '@sveltejs/kit/vite'; const config = { plugins: [sveltekit()], test: { include: ['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'], environment: 'jsdom', glo ...

Why is the reference of `this` pointing to `o` in this scenario (o.method)() rather than the global object?

Let's consider the scenario with an object: var o = { prop: 3, method: function() {return this.prop} } My expectation was that calling (o.method)() would result in undefined, but instead it returned 3, indicating that the reference of this ...

Angular HttpClient request fails to initiate

Overview: A button click on a form triggers the methodForm within the component. methodForm then calls methodService in the service layer. methodService is supposed to make an HTTP POST request. Problem: The HTTP POST request is not being made. However, me ...

Converting a JavaScript IIFE library into a React Component

Hello, I am currently in the process of learning React JS and there are two JavaScript files that I am working on: Polyfill.js -> hosted on github CustomNavbar.js -> created by me Here is the structure of polyfill.js: export default (function(window){ ...

What is the best way to incorporate arrow buttons on my website in order to unveil various sections on the homepage?

A colleague and I are collaborating on a website for his cookery business. He has sketched out some design ideas on paper, one of which involves having a homepage with 4 different sections stacked on top of each other. Each section would have an arrow butt ...

Limit Javascript Regex to accept only one specific possibility and exclude all others

Here are the specific validations I need for my URL: cars : valid cars/ : valid (Accepting any number of '/' after "cars") cars- : invalid cars* : invalid carsp : invalid (Rejecting any character after "cars" except '/') **cars/ne ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

Searching and updating a value in an array using JavaScript

I need help solving a Javascript issue I'm facing. I'm working on an e-commerce project built in Vue, and I want to implement the selection of product variants on the client-side. The data format being sent to the backend looks like this: { & ...

Firefox fails to apply styling to content loaded through Ajax (particularly when using AngularJS)

I've encountered a strange problem while working on my app (MVC4 + AngularJS). It seems that in Firefox (currently version 42), content loaded through an Ajax call does not always pick up the CSS styles that were loaded before. In the attached images, ...

Invoking RESTful services using parameters

Currently, I am tackling a project that involves coding in both Java and Angular. The request is sent from Angular with specified parameters, which I need to retrieve in the REST services on the Java side. While I am unable to alter the Angular component, ...

The MaterialTable is unable to display any data

After calling the fetch function in the useEffect, my getUsers function does not populate the data variable. I am unable to see rows of data in the MaterialTable as the data structure is in columns. I need help figuring out what I'm doing wrong. func ...