JavaScript Array Comparison Function

Question

I currently have a map of an array of users which all have a unique _id key / value.

user = [{_id: "1", ... }, {_id: "2", ... }, ... ]

I also have two other arrays, one named teams and another named accounts.

teams = [{ _id: "1", members: [{ userId: "2" }, { userId: "4" }, ... ], ... }]

accounts = [{ _id: "1", authorizedUsers: [{ userId: "3"}, ... ], ownerTeamId: "2" }, ... ]

Trying to create two comparison functions which takes the argument of user and outputs numberOfTeams and numberOfAccounts for the corresponding user.

I have attempted the numberOfTeams below but I'm not sure if it's the most optimal.

numberOfTeams(user) {
  let count = 0;
  teams.forEach(team => {
    team.members.forEach(member => {
      if (member.userId === user._id) {
        count++
      }
    })
  });
  return count;
}

With the numberOfAccounts, I'm stuck on how to compare authorizedUsers === user._id OR ownerTeamId === team._id where also members.userId === user.id, and then count++.


Show source
| javascript   | function   | arrays   | comparison   2017-01-06 03:01 1 Answers

Answers ( 1 )

  1. 2017-01-06 04:01

    It’s probably a good start to write a function to get the teams a user belongs to:

    function containsUserId(users, id) {
        return users.some(user => user.userId === id);
    }
    
    function getUserTeams(user, teams) {
        return teams.filter(team =>
            containsUserId(team.members, user._id));
    }
    

    because then you can write numberOfTeams using it:

    numberOfTeams(user) {
        return getUserTeams(user, teams).length;
    }
    

    then a similar function to get accounts:

    function getUserAccounts(user, accounts) {
        const userTeamIds = new Set(
            getUserTeams(user).map(team => team._id)
        );
    
        return accounts.filter(account =>
            containsUserId(account.authorizedUsers, user._id) ||
            userTeamIds.has(accounts.ownerTeamId));
    }
    

    then numberOfAccounts using it:

    numberOfAccounts(user) {
        return getUserAccounts(user, accounts).length;
    }
    

    Essentially: use more functions so you can understand the steps you’re taking to solve your own problem and, in doing so, use those steps more effectively.

◀ Go back