Remove duplicate elements from an array using AngularJS
Last Updated :
07 Aug, 2024
Improve
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 that 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.
<!DOCTYPE HTML>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
</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:
Video Player
00:00
00:00
Example 2: This example does the case-sensitive comparison, so the elements like ‘gfg’ and ‘GFG’ will not be considered as duplicates.
<!DOCTYPE HTML>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
</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:
Video Player
00:00
00:00