When using ng-repeat, make sure to track by $index for unique

After manipulating an array with 5 values (1, 2, 3, 4, 5), it now contains duplicate data (1, 2, 3, 4, 5, 1, 2, 3, 4, 5). I would like to use ng-repeat with $index to display the data without duplicates. Is this possible?

Answer №1

If you need to eliminate duplicates from a list, you can create a custom filter as shown below:

app.filter('unique', function() {

  return function(list) {

    var unique = function(origArr) {
      var newArr = [],
          origLen = origArr.length,
          found, x, y;

      for (x = 0; x < origLen; x++) {
          found = undefined;
          for (y = 0; y < newArr.length; y++) {
              if (origArr[x] === newArr[y]) {
                  found = true;
                  break;
              }
          }
          if (!found) {
              newArr.push(origArr[x]);
          }
      }
      return newArr;
    };

    return unique(list);

  }

});

After creating the filter, you can use it with ng-repeat:

<p ng-repeat="item in list | unique">List Item: {{ item }}</p>

For a working example, please check out this plunker: https://plnkr.co/edit/wklSOYJpHZxFlzCNPI9L?p=preview

Answer №2

To achieve a list of unique items in Angular, you can create a custom filter function like the one shown in this JSFiddle example

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

app.filter("uniqueItem", function() {
  return function(collection) {
    var output = [];
    angular.forEach(collection, function(item) {
      if (output.indexOf(item) === -1) {
        output.push(item);
      }
    });
    return output;
  };
});

<div ng-repeat="item in items | uniqueItem">List Item: {{ item }}</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to insert rows and columns into the table headers using React Material UI?

I am new to working with material UI and I am having trouble figuring out how to add columns in the table header. The image below shows what I am trying to achieve - under "Economics", there should be 3 columns, each of which will then have two more column ...

Tips for loading a partial view page in a specific element using Angular JS after clicking a button

I'm facing an issue with my AngularJS partial view page not loading after a button click. I've set up the initial rendering page, but when we click the button, the partial view page doesn't render properly because the angular modules are not ...

Having difficulty removing new or existing lines on StackBlitz

I attempted to experiment with React on StackBlitz, but I encountered a problem where I couldn't delete any lines of code. It seems that while I can add new lines of code, deleting them is not an option. Even when logging in with GitHub, the issue per ...