Open In App

Remove duplicate elements from an array using AngularJS

Last Updated : 01 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

We have given an array and the task is to remove/delete the duplicates from the array using AngularJS.

Approach: 

  • The approach is to use the filter() method and inside the method, the elements which don’t repeat themselves will be returned and the duplicates will be returned only once.
  • Hence, a unique array will be made.

Example 1: In this example, the character ‘g’ and ‘b’ are removed from the original array.

HTML




<!DOCTYPE HTML>
<html>
  
<head>
    <script src=
    </script>
  
    <script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function ($scope) {
            $scope.arr = ['g', 'a', 'b', 'c', 'g', 'b'];
            $scope.res = [];
            $scope.remDup = function () {
                $scope.res = $scope.arr
                    .filter(function (item, pos) {
                    return $scope.arr.indexOf(item) == pos;
                })
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
  
  
    <p>
        Remove duplicate elements from 
        the array in AngularJS
    </p>
  
    <div ng-app="app">
        <div ng-controller="controller">
            Original Array = {{arr}}
            <br><br>
            <button ng-click='remDup()'>
                Click here
            </button>
            <br><br>
            Final Array = {{res}}<br>
        </div>
    </div>
</body>
  
</html>


Output:

Example 2: This example does the case-sensitive comparison, so the elements like ‘gfg’ and ‘GFG’ will not be considered as duplicates.

HTML




<!DOCTYPE HTML>
<html>
  
<head>
    <script src=
    </script>
  
    <script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function ($scope) {
            $scope.arr = ['gfg', 'GFG', 
                'Gfg', 'gFG', 'gFg', 'gFg'];
            $scope.res = [];
            $scope.remDup = function () {
                $scope.res = $scope.arr
                    .filter(function (item, pos) {
                    return $scope.arr.indexOf(item) == pos;
                })
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
  
  
    <p>
        Remove duplicate elements 
        from the array in AngularJS
    </p>
  
    <div ng-app="app">
        <div ng-controller="controller">
            Original Array = {{arr}}
            <br>
            <br>
            <button ng-click='remDup()'>
                Click here
            </button>
            <br>
            <br>
            Final Array = {{res}}<br>
        </div>
    </div>
</body>
  
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads