javascript – 根据多个数组输入过滤数组

我有三个阵列.
1.现有的查看器数组 – existingViewers

>新观众阵列 – newViewers
>允许的查看者数组 – allowedViewers

allowedViewers用于呈现下拉列表.我希望从allowedViewers中过滤newViewers和existingViewers条目.

我这样做是三步.而且我担心这不是优化的方式.有人可以提出理想的做法吗?
预期的结果是

[
  {
    "id": 4,
    "name": "name4"
  },
  {
    "id": 5,
    "name": "name5"
  },
  {
    "id": 6,
    "name": "name6"
  }
]
let existingViewers = [{
      "viewerId": 1,
      "name": "name1"
    },
    {
      "viewerId": 2,
      "name": "name2"
    }
  ],
  newViewers = [

    {
      "viewerId": 3,
      "name": "name3"
    }
  ],
  permittedViewers = [{
      "id": 1,
      "name": "name1"
    },
    {
      "id": 2,
      "name": "name2"
    },
    {
      "id": 3,
      "name": "name3"
    },
    {
      "id": 4,
      "name": "name4"
    },
    {
      "id": 5,
      "name": "name5"
    },
    {
      "id": 6,
      "name": "name6"
    }
  ]
let grouped = [...existingViewers, ...newViewers]

let viewerFilter = grouped.map(viewer => { return viewer.viewerId; });

let filteredPermittedViewers = permittedViewers.filter(viewer => !viewerFilter.includes(viewer.id));

console.log(filteredPermittedViewers)

解决方法:

我创建了前两个数组的ID的集合,然后根据集合是否包含id来过滤第三个数组. (设置有O(1)查找时间)

let existingViewers=[{"viewerId":1,"name":"name1"},{"viewerId":2,"name":"name2"}],newViewers=[{"viewerId":3,"name":"name3"}],permittedViewers=[{"id":1,"name":"name1"},{"id":2,"name":"name2"},{"id":3,"name":"name3"},{"id":4,"name":"name4"},{"id":5,"name":"name5"},{"id":6,"name":"name6"}];

const ids = new Set([...existingViewers, ...newViewers].map(({ viewerId }) => viewerId));
const output = permittedViewers.filter(({ id }) => !ids.has(id));
console.log(output);
上一篇:phpMyAdmin:MySQL错误1062 – 重复输入


下一篇:mysql – 在列中的每个副本上递增计数器