Array filtering with array in AngularJS

I tried to filter a group of checkboxes with such an array:

<ion-checkbox ng-repeat="user in users | filter: {id: group.members}" ng-model="user.checked">{{user.info.name}}</ion-checkbox>

where group.members is an array of user.id and it shows nothing.

Users:

[12345,123456]

group.members Array:

[12345]

I try to not show group.members in the users list, because in this case the user is trying to invite another user to the group and why invite someone who is already a member?

I tried to create my own filter, but its just a mess:

 .filter('existingMembers', function() { return function(users, members) { return users.filter(function(user) { for (var i in user.id) { if (members.indexOf(user.id[i]) != -1) { return; } } return user; }); }; }) 
+5
source share
2 answers

After some mess, this is the solution. See plunkr for a working example. I think this should do the trick:

Template:

 <ion-checkbox ng-repeat="user in users | filter: excludeMembers:group.members" ng-model="user.checked">{{user.info.name}}</ion-checkbox> 

Angular filter:

 app.filter('excludeMembers', function(){ return function(users, members){ return users.filter(function(user){ return members.indexOf(user.id) === -1; }); } }) 

Long explanation

The filter takes an array into which you filter as the first parameter, by default, and then with a colon (:), you can provide optional arguments, in your case: group. The filter should return the function that will be launched. The return value must be a filtered array. We also use the built-in javascript filter (confusing, whoa) function to validate a group array.

+2
source

Using the look up table (LUT) object, you can do filtering like this with pure JS.

 var gmems = [12345, 567890], users = [12345,123456,432567,1234987,567890], lut = gmems.reduce((p,c) => {p[c]=true; return p},{}), res = users.filter(e => !lut[e]); document.write('<pre>' + JSON.stringify(res, 0, 2) + '</pre>'); 
0
source

Source: https://habr.com/ru/post/1247868/


All Articles