0

Have a set of objects in an array (items array) that have property

item_id:
[{item_id:1,...},{item_id:2,...}...]

Have another array with a set of

item_ids:
[2, 8, 10]

How do I use the $filter of angularjs to get array of objects from items array where item_id matches those in item_ids array.

1 Answer 1

1

You can use custom filter to do this kind of filtration. and you can use use $filter service if you want to do that in code instead of template.

Filter Guide

See the below code.

var app = angular.module('app', []);

app.controller('ctrl', function($scope, $filter) {

  $scope.items = [{
    item_id: 1
  }, {
    item_id: 2
  }, {
    item_id: 3
  }, {
    item_id: 4
  }];

  $scope.findList = [2, 4];
  $scope.findList2 = [3];

  // Using $filter service.
  $scope.usingservice = $filter('findobj')($scope.items, [1, 3])
});

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

  return function(list, obj) {

    return list.filter(function(l) {
      if (obj.indexOf(l.item_id) >= 0) {
        return true;
      }
    });

  };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="ctrl">
    <div ng-repeat="item in items | findobj: findList">
      {{item}}
    </div>
    <hr/>
    <div ng-repeat="item in items | findobj: findList2">
      {{item}}
    </div>
    <hr/>{{usingservice}}
  </div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Wanted to do this in code using $filter, as shown in your example. Didn't know array could be used instead of filter condition. The other part (using with ng-repeat) also very useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.