I'm using Angular. I'm trying to compare two arrays of objects I was able to get it working doing it like this:
var compareUsers = function () {
//Comparing assigned groups with all to return available users
var assignedUsersIds = {};
var usersIds = {};
availableUsers = []; //declared higher up, populated with user objects on load
//assignedUsers, declaired higher up, populated by function calling compareUsers
assignedUsers.forEach(function (el, i) {
assignedUsersIds[el.id] = assignedUsers[i];
});
allUsers.forEach(function (el, i) {
usersIds[el.id] = allUsers[i];
});
for (var i in usersIds) {
if (!assignedUsersIds.hasOwnProperty(i)) {
availableUsers.push(usersIds[i]);
}
};
console.log(availableUsers);
return availableUsers;
}
I found a better way to do it so I refactored it to this, using lodash
:
var compareUsers = function () {
availableUsers = _.filter(allUsers, function(user){
return !_.findWhere(assignedUsers, user);
});
console.info(availableUsers);
return availableUsers;
}
However, I'm not getting the correct results and not sure what I messed up. The new methods returns availableUsers
which are in the assignedUsers
list for some groups. The first time it runs, it seems to work but if I keep changing what group i'm looking at the results are all off and don't add up.
I found this method here.