Angularjs filter to filter array items by type

When iterating over array items in an ‘ng-repeat’, we often want to filter out some items. Here is an angular filter to do the same.

Usage

Use the filter as follows to only include the array items with the given type.
// Include items with type 'XYZ'
filterByType: { name: 'itemtype', type: 'XYZ' }
To omit items with the given type, precede the type with ‘!’.
// Exclude items with type 'XYZ'
filterByType: { name: 'itemtype', type: '!XYZ' }

Example

<!-- Include items with type 'FOOD' -->
<div class="all" ng-repeat="item in filteredFoodList = (items.list | filterByType: {name: 'mealtype', type:'FOOD'})">
	<food-summary data="item"></food-summary>
</div>

<!-- Exclude items with type 'FOOD' -->
<div class="all" ng-repeat="item in filteredNonEdibleList = (items.list | filterByType: {name: 'mealtype', type:'!FOOD'})">
	<food-summary data="item"></food-summary>
</div>

Code

angular.module('TestFilter', []).
filter('filterByType', function() {
  /**
   * Returns items by type and excludes if type is prefixed with '!'
   */
  return function(items, typeinfo) {
    var isFilterInverse = false;
    if (typeinfo.type.charAt(0) == '!') {
      typeinfo.type = typeinfo.type.substr(1);
      isFilterInverse = true;
    }

    var filtered = [];
    for (var index in items) {
      var item = items[index]
      if (isFilterInverse == false) {
        if (item[typeinfo.name] == typeinfo.type) {
          filtered.push(items[index]);
        }
      } else {
        if (item[typeinfo.name] != typeinfo.type) {
          filtered.push(items[index]);
        }
      }
    }
    return filtered;
  }
});
Do let us know if you found this useful. Happy Coding !!!