0

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++.

1
  • numberOfAccounts property does not appear at javascript objects at Question? What is numberOfAccounts referencing, members array? Commented Jan 6, 2017 at 2:54

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.