Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  144] [ 1]  / answers: 1 / hits: 22947  / 11 Years ago, sun, january 19, 2014, 12:00:00

I have two arrays which only contain objects for groups. One contains all the groups on my site. The other contains all the groups a specific user belongs to.



I'd like to subtract: All the groups - user groups = groups remaining



I'm using AngularJS, I'm not sure if that helps here or not (maybe a filter could be used).



I looked at previous questions and came across some options:



These are the ones I tried:



$scope.availableGroups =  $($scope.groups).not($scope.assignedGroups).get();
$scope.availableGroups = $.grep($scope.groups,function(x) {return $.inArray(x, $scope.assignedGroups) < 0})


This is one of the arrays:



assignedGroups:



[{
id: 115,
name: 'Test Group 2',
Description: '',
owner: 10,
OwnerIsUser: false,
}, {
id: 116,
name: 'Test Group 3',
Description: '',
owner: 71,
OwnerIsUser: false,
}, {
id: 117,
name: 'Test Group 4',
Description: '',
owner: 71,
OwnerIsUser: false,
}, {
id: 118,
name: 'Test Group 5',
Description: '',
owner: 115,
OwnerIsUser: false,
}, {
id: 119,
name: 'Test Group 6',
Description: '',
owner: 8,
OwnerIsUser: true,
}];

More From » jquery

 Answers
58

I think you should extract ids to an object first and then compare two objects. Eg:



var assignedGroupsIds = {};
var groupsIds = {};
var result = [];

$scope.assignedGroups.forEach(function (el, i) {
assignedGroupsIds[el.id] = $scope.assignedGroups[i];
});

$scope.groups.forEach(function (el, i) {
groupsIds[el.id] = $scope.groups[i];
});

for (var i in groupsIds) {
if (!assignedGroupsIds.hasOwnProperty(i)) {
result.push(groupsIds[i]);
}
}

return result;


Here goes simplified fiddle: http://jsfiddle.net/NLQGL/2/
Adjust it to your needs.



I think it's a good solution since you could reuse the groupsIds object (it seems not to change often).



Note: Feel free to use angular.forEach() instead of Array.prototype.forEach


[#73073] Friday, January 17, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gilbertomaximilianod

Total Points: 208
Total Questions: 96
Total Answers: 111

Location: Northern Mariana Islands
Member since Wed, Feb 24, 2021
3 Years ago
;