How to get unique values in array Angularjs?

To get unique values in an array in AngularJS, you can create a custom filter. Here’s an example of how to create a filter to get unique values from an array:

  1. Create an AngularJS module and a custom filter called ‘unique’:

JS

angular.module('app', [])
  .filter('unique', function() {
    return function(collection, key) {
      var output = [],
          keys = [];

      angular.forEach(collection, function(item) {
        var keyValue = key ? item[key] : item;
        if (keys.indexOf(keyValue) === -1) {
          keys.push(keyValue);
          output.push(item);
        }
      });

      return output;
    };
  });

In this example, we create a filter called ‘unique’ that takes an array (collection) and an optional key as arguments. The filter iterates through the collection and adds unique items (or unique item properties if a key is provided) to the output array.

  1. Use the ‘unique’ filter in your HTML:

HTML

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="MainController">
    <p>Original Array: {{ items }}</p>
    <p>Unique Array: {{ items | unique }}</p>
  </body>
</html>
  1. Create an AngularJS controller with a sample array:

JS

angular.module('app')
  .controller('MainController', function($scope) {
    $scope.items = [1, 2, 3, 4, 4, 5, 5, 6, 1, 2];
  });

In this example, we create a ‘MainController’ and define an array of items with duplicate values. In the HTML file, we use the ‘unique’ filter to display the unique values from the ‘items’ array.

When you run this example, you’ll see the original array and the array with unique values displayed on the page.

Facebook
Twitter
LinkedIn
Pinterest

Related posts