JavaScript数组比较函数

时间:2017-01-06 02:52:12

标签: javascript arrays function comparison

我目前拥有一组map个用户,这些用户都拥有唯一的_id键/值。

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

我还有另外两个数组,一个名为teams,另一个名为accounts

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

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

尝试创建两个比较函数,其中user的参数为numberOfTeams输出numberOfAccountsuser

我尝试过下面的numberOfTeams,但我不确定它是否是最优的。

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

使用numberOfAccounts,我仍然坚持如何比较authorizedUsers === user._id ownerTeamId === team._id,其中members.userId === user.id,然后{{1 }}

1 个答案:

答案 0 :(得分:3)

编写一个函数来获取用户所属的团队可能是一个良好的开端:

function containsUserId(users, id) {
    return users.some(user => user.userId === id);
}

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

因为那样你可以用它来写numberOfTeams

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

然后有类似的功能来获取帐户:

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));
}

然后numberOfAccounts使用它:

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

基本上:使用更多功能,这样您就可以了解解决自身问题所采取的步骤,并在此过程中更有效地使用这些步骤。