Could someone provide some clarity on this piece of code?

I'd really appreciate it if someone could break down this snippet of code for me. It's an angular filter with the module name ui.filters.

angular.module('ui.filters').filter('unique', function () {

  return function (items, filterOn) {

    if (filterOn === false) {
        return items;
    }

    if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
        var hashCheck = {}, newItems = [];

        var extractValueToCompare = function (item) {
            if (angular.isObject(item) && angular.isString(filterOn)) {
                return item[filterOn];
            } else {
                return item;
            }
        };

        angular.forEach(items, function (item) {
            var valueToCheck, isDuplicate = false;

            for (var i = 0; i < newItems.length; i++) {
                if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
                    isDuplicate = true;
                    break;
                }
            }
            if (!isDuplicate) {
                newItems.push(item);
            }

        });
        items = newItems;
    }
    return items;
  };
});

Answer №1

Hey there, Rajesh! Feel free to check out this working plunker of the filter here.

I've made some updates including correcting declarations and removing any unused variables.

angular.module('ui.filters',[]).filter('unique', function () {

  return function (items, filterOn) {

    // If filterOn is false, return items as they are
    if (filterOn === false) {
        return items;
    }

    // Execute this loop when "filterOn = defined/undefined AND items is an array"
    if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
        var newItems = [];

        var extractValueToCompare = function (item) {
            // Check if item is an object AND filterOn is a string
            if (angular.isObject(item) && angular.isString(filterOn)) {
                return item[filterOn];
            } else {
                return item;
            }
        };

        angular.forEach(items, function (item) {
            var isDuplicate = false;
            for (var i = 0; i < newItems.length; i++) { 
                // Push new values into newItems only if they are not duplicates
                if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
                    isDuplicate = true;
                    break;
                }
            }
            
            if (!isDuplicate) {
                newItems.push(item);
            }

        });
        
        items = newItems;
    }
    
    return items;
  };
});

Use console.log to verify different values in each iteration

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

When is it necessary to provide the array size as an argument?

I'm feeling a bit lost when it comes to passing an array in C/C++. I've noticed different signatures such as: void f(int arr[]) and some like this: void f(int arr[], int size) Can someone explain the difference between them and help clarify w ...

Use an input to swap out a cube for a sphere in three.js

I need to switch the cube with a sphere of the same size, but when I try to add a function in JavaScript, the cube disappears. How can I adjust the dimensions of the cube? I am unsure how to connect the function modifie with the numeric inputs (length, w ...

Error message "process is not defined" encountered following upgrade to Next.js version 12 from 11.x.x

Encountering an issue after updating to the newest version 12 from 11.x.x Error: ReferenceError: process is not defined This is my updated package.json: { "name": "tnhc-fe", "version": "0.1.0", "private ...

Update the reference of the 'this' keyword after importing the file

I am currently utilizing react-table to showcase the data. My intention is to house my table columns outside of the react component due to its size and for reusability purposes. I created a table configuration file to contain all of my table configurations ...

Issue for Codepen/JS beginners: Uncaught ReferenceError - 'exports' variable is undefined

After getting a Pen directly from the tutorial, I noticed it included some external scripts: https://unpkg.com/react/umd/react.development.js https://unpkg.com/react-dom/umd/react-dom.development.js The initial code snippet I tried worked smoothly: const ...

What could possibly be causing my ng-model and ng-selected to be disregarded by my select

Having an issue with a select box that is not selecting the option bound to ng-model or ng-select. Instead, it initially selects the hard coded value but then overrides my selection with the last item in the list. Even after stripping it down to its bare m ...

Struggling with passing parameters through an Ajax request in a Rails application

I've been scratching my head trying to pinpoint the issue here - my goal is to send an ajax request with some data and then display a modal form: var position = $(".exercise-list").sortable('toArray'); var positionData = "["+position+"]" $ ...

Encountered an error in AWS Lambda (Node 14.x): SyntaxError - Unexpected token 'export'

As I work on developing a straightforward login and registration system with AWS, I encountered an issue in AWS Lambda while testing my backend using Postman. The error code is detailed below: { "errorType": "Runtime.UserCodeSyntaxError& ...

A step-by-step guide on how to use the Google Closure Compiler: a

Is there anyone who could assist me in adding a snippet to the basic process of Google Closure Compiler? I have been trying unsuccessfully to do this via JavaScript code. I am using an example snippet from the official npm page, but when I run it, someth ...

What is the best way to attach a click event listener to dynamically generated child elements?

My parent container houses a variable number of elements generated by an API as the user inputs text. These elements, in turn, serve as parents to other child elements. The goal is for an overlay with more details about a specific element to appear when t ...

Updating classes in a CSS style for a chosen item, and modifying additional classes for similar elements to match the selected one

How can I apply the 'selected' class to only the clicked item and remove it from all other items with similar classes? <ul class="nav-list"> <li> <a href="#"> <i class="fa-soli ...

Relaunch jQuery script on dynamically loaded content via AJAX requests

Currently, I am utilizing the Advanced Ajax Page Loader plugin for wordpress to dynamically load content through ajax. However, I am encountering an issue where my custom jquery scripts do not execute properly when the content is loaded via ajax. Interesti ...

Calculating the mean value from a JSON array

I'm having trouble calculating the average from my variable output. I keep getting NaN or zero as a result. Here is my initial output: console.log(data) 0: {nodeId: "53", SNR: "[38.2, 38, 37.9, 37.8, 37.6]", timestamp: "2019-09-05 00:00:17"} Next, ...

Is there a way to achieve this in the C programming language?

I created a BMI (Body Mass Index) Calculator program that collects weight and height inputs from 10 users, calculates the BMI, and displays the results in a formatted output. Here is an example of the desired format: USER BMI ...

SheetJS excel-cell customization

I'm using this example to export a worksheet from https://github.com/SheetJS/js-xlsx/issues/817. How can I apply cell styling such as background color, font size, and adjusting the width of cells to fit the data perfectly? I have looked through the do ...

What is the best way to navigate to the top of a form panel?

I'm currently developing a Sencha Touch mobile app. I have a form panel with multiple fields, so I made it scrollable. However, every time I open the screen (panel), scroll down, navigate to other screens, and then return to the form panel, it stays s ...

What could be causing the 304 error when using $http.get?

I'm a newcomer to angular and facing an issue with a service that was functioning perfectly, but suddenly stopped. The service I am referring to has the following method. this.retrieveForms = function() { return $http.fetch("/forms"). then(fu ...

Using a bound data variable in a filter within an ng-repeat loop (Angular JS)

<!-- Left Navbar --> <div class="container-fluid" style="margin-top: 50px"> <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <ul ng-repeat="type in types" class="nav nav-sidebar"> <li>{{ ...

Tips for sharing invites with friends through the Facebook instant game SDK using the Phaser framework

Currently, I am in the midst of developing a Facebook instant game project. It has come to my attention that I need to include friend invites in my instant game, which is built using the Phaser framework. Unfortunately, after conducting a thorough search, ...

When using Angular's ng-repeat, data binding may not work properly for arrays that are created dynamically

I've encountered a bug that I've been trying to troubleshoot with various solutions from StackOverflow, but nothing seems to work, such as: 1) Using $rootScope Array. 2) Implementing $scope.$apply() (after realizing it's not ideal due to a ...