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’:


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) {

      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:


<!DOCTYPE html>
<html ng-app="app">
    <script src=""></script>
    <script src="app.js"></script>
  <body ng-controller="MainController">
    <p>Original Array: {{ items }}</p>
    <p>Unique Array: {{ items | unique }}</p>
  1. Create an AngularJS controller with a sample array:


  .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.


Table of Contents

Related posts