What is the best way to eliminate repetitive keys in AngularJS ng-repeat?

I am implementing ng-repeat for an array JSON value. However, I am facing an issue with duplicate values being displayed in the UI (HTML). Specifically, the "Car" value is repeating and I want to remove duplicate key values so that it appears only once.

var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope){
   $scope.res ={};
   $scope.res.fsus = [
  {
    "statusMessageType": {
      "MasterConsignment": {
        "ReportedStatus": {
          "ReasonCode": "var"
        }
      }
    }
  },
  {
    "statusMessageType": {
      "MasterConsignment": {
        "ReportedStatus": {
          "ReasonCode": "car"
        }
      }
    }
  },
  {
    "statusMessageType": {
      "MasterConsignment": {
        "ReportedStatus": {
          "ReasonCode": "car"
        }
      }
    }
  },
  {
    "statusMessageType": {
      "MasterConsignment": {
        "ReportedStatus": {
          "ReasonCode": "car"
        }
      }
    }
  },
  {
    "statusMessageType": {
      "MasterConsignment": {
        "ReportedStatus": {
          "ReasonCode": "ban"
        }
      }
    }
  }
];
 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp" ng-controller="testCtrl">
<li ng-repeat="test in res.fsus track by $index">
  <span class="step">    {{test.statusMessageType.MasterConsignment.ReportedStatus.ReasonCode}}
  </span> 
</li>
</body>

Answer №1

To eliminate duplicate elements, there is no need for any external library. You can achieve this by using angular.forEach method.

angular.forEach($scope.res.fsus,function(key,value){
  if(($scope.opts.indexOf(key.statusMessageType.MasterConsignment.ReportedStatus.ReasonCode , 0)) <= -1){    $scope.opts.push(key.statusMessageType.MasterConsignment.ReportedStatus.ReasonCode);
  };
});

DEMO

var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope){
   $scope.res ={};

   // Data Sample
   $scope.res.fsus = [
  {
    "statusMessageType": {
      "MasterConsignment": {
        "ReportedStatus": {
          "ReasonCode": "var"
        }
      }
    }
  },
  {
    "statusMessageType": {
      "MasterConsignment": {
        "ReportedStatus": {
          "ReasonCode": "car"
        }
      }
    }
  },
  {
    "statusMessageType": {
      "MasterConsignment": {
        "ReportedStatus": {
          "ReasonCode": "car"
        }
      }
    }
  },
  {
    "statusMessageType": {
      "MasterConsignment": {
        "ReportedStatus": {
          "ReasonCode": "car"
        }
      }
    }
  },
  {
    "statusMessageType": {
      "MasterConsignment": {
        "ReportedStatus": {
          "ReasonCode": "ban"
        }
      }
    }
  }
];

$scope.opts = [];
angular.forEach($scope.res.fsus,function(key,value){
  if(($scope.opts.indexOf(key.statusMessageType.MasterConsignment.ReportedStatus.ReasonCode , 0)) <= -1){    $scope.opts.push(key.statusMessageType.MasterConsignment.ReportedStatus.ReasonCode);
  };
});

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<body ng-app="testApp" ng-controller="testCtrl">
<li ng-repeat="test in opts">
  <span class="step">    {{test}}
  </span> 
</li>
</body>

Answer №2

To eliminate identical objects from a collection of objects, you can utilize lodash's _.uniqWith in conjunction with _.isEqual. Learn more about it on the official documentation page for lodash uniqWith.

var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope){
  $scope.res ={};
  fake = ['var', 'car', 'car', 'ban', 'car']
  $scope.res.fsus = fake.map( val => {
    return {
      "statusMessageType": {
        "MasterConsignment": {
          "ReportedStatus": {
            "ReasonCode": val
          }
        }
      }
    };
  })
  $scope.res.fsus = _.uniqWith($scope.res.fsus, _.isEqual);
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8083888d9f84acd8c2dddbc2d8">[email protected]</a>/lodash.min.js"></script>
<body ng-app="testApp" ng-controller="testCtrl">
  <li ng-repeat="test in res.fsus track by $index">
    <span class="step">
      {{ test.statusMessageType.MasterConsignment.ReportedStatus.ReasonCode }}
    </span> 
  </li>
</body>

Note: While @Sajeetharan suggests using native code over external libraries, if you are already utilizing lodash elsewhere in your project as I am, it may be beneficial to continue using lodash in this scenario as well.

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

I'm struggling to comprehend the purpose of this function. [From the Codecademy Contact List exercise]

Within the "for var x in friends" loop, the program aims to search each key within the friends object, such as bill and steve. Subsequently, with the condition "friends[x].firstName === name", the check is made if the first name matches the provided inpu ...

Leveraging jQuery's Append functionality

Struggling with using jQuery's .append() method. Check out my code: $('#all ul li').each(function() { if ($(this).children('.material-icons').hasClass('offline-icon') == false) { $('#online ul').append ...

Troubleshooting: Unable to load template file content in AngularJS ng-view

Setting up a demo angular app has been quite the challenge for me. Despite my efforts, the content from my partial file (partials/test.html) is not loading into the layout file as expected. Below is a snippet of my index.html: <!DOCTYPE html> <ht ...

JSON function invocation is failing to load

This is my JavaScript script, When I call the function calculate(), the JSON method ConvertDataTabletoString() only gets called once, when I load the page. I want the method to be called every 5 seconds. I am calling a VB.NET function in .aspx. How can ...

Is there a way to simulate pressing the ENTER/RETURN key using JavaScript executor in Selenium using Python?

Greetings everyone, I am a newcomer to Python Selenium and currently working on automating a website. However, I have encountered an issue with the search text box of the website as it does not feature any clickable buttons once the text is entered. Here ...

What is the best way to form a singular entity and insert numerous sets of key-value pairs within it?

Currently, I am working on creating an object that contains multiple key-pair values obtained from an API response. My goal is to transform the API response into a single object, but the code I have written does not produce the desired result. This is my ...

Should items be added or removed from the list when the toggle is activated or deactivated?

$(document).ready(function() { var materials = []; var limit = $("#upper").val(); $("#upper").change(function() { limit = $(this).val(); }); $(".u").click(function() { var color = $(this).attr('data-color'); var id = $(thi ...

Is there a way for me to acquire the Amazon Fire TV Series?

I'm currently working on developing a web app for Amazon Fire TV, and I require individual authorization for each app. My plan is to utilize the Amazon Fire TV serial number for this purpose. However, I am unsure how to retrieve this serial using Jav ...

Is there a more efficient way to consolidate multiple functions like this into one cohesive function instead of having to define each one separately?

After attempting to implement a loop without success, I also considered using regex but that did not work either. The code in question is part of a larger project that involves dynamically adding and deleting fields using jQuery. The classes and ids used f ...

Issue: Avoid creating functions inside loops

I am struggling to update variables in an email template. Here is the code I have been working on: Unfortunately, I keep encountering the "error: Don't create functions within a loop" var dataPlaceholders = [{ "username":"John Johny", ...

Display or conceal a field depending on the user's input

I need to display a checkbox only when the firstname matches abc or if the email is [email protected]. var x = abc; //will be dynamic var y = abc @gmail.com jQuery("#firstname").on('change', (function(avalue) { return function(e) { ...

Error with retrieving nested JS script using $.getScript occurs sporadically

Attempting to load all nested JS files on click in order to trigger an event. I have tried this approach but keep encountering random script failures. Oddly, it works flawlessly in Fiddle at times and fails randomly. In addition to this, I need to load a ...

Even though I am aware that the variable AJAX is attempting to return is not empty, it is still returning 'undefined'

I wrote a basic PHP script that retrieves information from a database and stores it in a multidimensional array: <?php //PHP code to fetch data from DB error_reporting(E_ALL); $db = new mysqli("localhost","root","pass", "Media") ...

Encountering an error in mapping loops using React and TypeScript interface

I'm currently working on implementing a map loop in JavaScript, and here's what I have so far: interface RoutesType { path: string; name: string; icon: string; layout: string; } This is the code for the map loop: // This function creat ...

Is there a tool or software available that can securely encode a text file into an HTML file without the need for loading it using AJAX?

At the moment, I'm using jQuery to load a txt file (in utf-8) via $.ajax. The txt file has some break lines, such as: line1 line2 line3 When loaded through AJAX into a variable, it appears as: line1\n\nline2\nline3 I could manuall ...

Dealing with React Native: Navigating App Store Rejections and Embracing IPv6

In my react-native client for a website, the login page offers two options: manually enter the login code or scan it using a barcode scanner. I have extensively tested the app on real devices and emulators, and it's functioning correctly. However, all ...

Using React Native to implement a slide bar that displays an image

Currently working on an app and aiming to implement a slider feature for emoji selection. Despite searching for suitable packages, I have not been able to find one that fits my requirements. As a result, I decided to use the react native slider instead. Ho ...

Storing duplicate code in multiple cache files using ReactJS ServiceWorker

I am currently working on integrating a serviceworker into an existing React application that has the following filesystem layout: Filesystem The initialization code is stored in the public folder, while the main code resides in the src folder. In my serv ...

Troubleshooting: Problems with Angular 2's [hidden] and *NgIf functionalities

My table displays a green circle if data is available in the gegevensAanwezig variable, which contains a school name, school code, and various booleans (Entreetoets, Eindtoets, etc) to indicate data availability. <tr *ngFor="let g of gegegevens ...

What is the best way to switch from one HTML file to its associated JavaScript and CSS files once a specific event is activated?

Is my approach to organizing and building my first website game correct? I have 5 separate HTML files along with their respective JS and CSS files. My goal is to slide in the content from the next HTML file, including its corresponding JS and CSS files, wh ...