如何区分两个数组?

时间:2019-05-28 15:40:36

标签: javascript

我只想得到不是朋友的用户

我有两个列表,朋友和用户, 如果他们已经是朋友,则用户列表应该不再存在

0

我可以在FILTER函数中使用FOR吗?是正确的吗?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,则您的friends数组是关系的列表。所以

{
  friend: {id: 3, name: "tres"},
  owner: {id: 1,  name: "uno"}
}

表示用户ID 1是用户ID 3的朋友。

因此要检查集合,只需使用Array.prototype.someArray.prototype.every中的哪一个更好看:

const friendless = (users, friends) =>
  users.filter(user => !friends.some(relationship => relationship.friend.id === user.id))

let users = [
  {id: 1, name: "uno"},
  {id: 2, name: "dos"},
  {id: 3, name: "tres"}
]

let friends = [{
  friend: {id: 3, name: "tres"},
  owner: {id: 1,  name: "uno"}
},{
  friend: {id: 2, name: "dos"},
  owner: {id: 1, name: "uno"}
}, {
  friend: {id: 3, name: "tres"},
  owner: {id: 2, name: "dos"}
}];


console .log (
  friendless (users, friends)
)

(或类似这样:

const friendless = (users, friends) =>
  users.filter(user => friends.every(relationship => relationship.friend.id !== user.id))

更新

我不知道您是否控制着usersfriends的结构,但是如果可以,您可能想重新考虑数据结构。您当前的方法似乎有很多不必要的重复。

以下任何一种方法都可以清除它:

A

let users = [
  {id: 1, name: "uno"},
  {id: 2, name: "dos"},
  {id: 3, name: "tres"}
]

let friends = [
  {id: 1, friend: 3},
  {id: 1, friend: 2},
  {id: 2, friend: 3},
];

B

let users = [
  {id: 1, name: "uno"},
  {id: 2, name: "dos"},
  {id: 3, name: "tres"}
]

let friends = [
  [1, 3],
  [1, 2],
  [2, 3],
];

C

let users = [
  {id: 1, name: "uno", friends: [3, 2]},  // (or `friendIds`)
  {id: 2, name: "dos", friends: [3]},
  {id: 3, name: "tres", friends: []}
]

选项C对于您当前的问题特别有用:

const friendless = users => users.filter(u => u.friends.length === 0)