Batman
Batman

Reputation: 6373

Difference between array of objects in Angularjs

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.

Upvotes: 1

Views: 1290

Answers (1)

FlorianTopf
FlorianTopf

Reputation: 948

In the first example you are using Array.push, which is always adding up (obviously), no matter how often you call compareUsers.

In the second example you are overwriting availableUsers each time you are calling compareUsers with the result of _.filter

I'd suggest that instead of doing:

availableUsers = _.filter(allUsers, function(user){
    return !_.findWhere(assignedUsers, user);
});

you do:

availableUsers = availableUsers.concat(_.filter(allUsers, function(user){
    return !_.findWhere(assignedUsers, user);
}));

This should work. It will concat the availableUsers array with the result of _.filter.

Upvotes: 1

Related Questions