I have a very simple array that has duplicate values. My array is like this:
$scope.type= ["Bar", "Pie", "Line", "Line", "Line", "Line", "Line", "Line", "map", "Line", "Bar", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie"]
in my ng-repeat, I have this condition
ng-repeat = types in type track by $index
How can I display only the unique values from my array in ng-repeat?
You can use unique filter while using ng-repeat.
ng-repeat="type in types|unique: type"
var app = angular.module('myApp',['ui.directives', 'ui.filters']);
app.controller("myCtrl", function($scope) {
$scope.types = ["Bar", "Pie", "Line", "Line", "Line", "Line", "Line", "Line", "map", "Line", "Bar", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui/0.4.0/angular-ui.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="type in types|unique: type">{{type}}</div>
</body>
If you don't want to include Lodash, you can do this:
$scope.typeUnique = Object.keys($scope.type.reduce((acc, val) => { acc[val] = true; return acc; }, {}));
Try this loop :
$scope.type= ["Bar", "Pie", "Line", "Line", "Line", "Line", "Line", "Line", "map", "Line", "Bar", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie"];
var output = [];
angular.forEach($scope.type, function(type, index) {
// if it's not already part of our keys array
if(output.indexOf(type) === -1) {
// push this item to our final output array
output.push(item);
}
});
Use lodash for convert your array to unque element array
$scope.type = _.uniq($scope.type);
To use loadsh you need to use cdn for lodash
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
To achieve expected result first sort and then filter with ng-if
<ul>
<li ng-repeat="x in sortedType = (type | orderBy) track by $index" ng-if="sortedType[$index -1] != x">
{{ x }}
</li>
</ul>
code sample - https://codepen.io/nagasai/pen/bvVMvV
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.type= ["Bar", "Pie", "Line", "Line", "Line", "Line", "Line", "Line", "map", "Line", "Bar", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie", "Pie"]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
<ul>
<li ng-repeat="x in sortedType = (type | orderBy) track by $index" ng-if="sortedType[$index -1] != x">
{{ x }}
</li>
</ul>
</div>
</body>
来源:https://stackoverflow.com/questions/49247681/remove-duplicate-from-ng-repeat