首页 > 解决方案 > 如何从 JavaScript 中的嵌套数组中过滤两个字段

问题描述

给定边缘,我想排除具有两个节点点的任何边缘。

nodes = ['1', '2', '3', '4']

edges = [
    {id: 'a', src: '1', target: '2'}, <<exclude cuz '1', '2' are in nodes
    {id: 'b', src: '4', target: '3'}, <<exclude
    {id: 'c', src: '1', target: '5'}, <<DO NOT exclude cuz only '1' is in nodes
    {id: 'd', src: '6', target: '2'}, <<DO NOT
    {id: 'e', src: '6', target: '8'}, <<DO NOT
]

output = ['c', 'd', 'e']

你能完成下面的陈述..?或者你有什么有效的解决方案?

nodes = ['1', '2', '3', '4']

edges = [
    {id: 'a', src: '1', target: '2'}, //exclude cuz '1', '2' are in nodes
    {id: 'b', src: '4', target: '3'}, //exclude
    {id: 'c', src: '1', target: '5'}, //DO NOT exclude cuz only '1' is in nodes
    {id: 'd', src: '6', target: '2'}, //DO NOT
    {id: 'e', src: '6', target: '8'}, //DO NOT
]

console.log(edges.filter({src, target} => nodes.includes(src) && nodes.includes(target)).map({id}=>id));

标签: javascript

解决方案


只需反转测试!以删除元素,而不是在它们符合条件时保留它们。

而且我已经修复了你的解构参数列表的语法。

nodes = ['1', '2', '3', '4']

edges = [
    {id: 'a', src: '1', target: '2'}, //exclude cuz '1', '2' are in nodes
    {id: 'b', src: '4', target: '3'}, //exclude
    {id: 'c', src: '1', target: '5'}, //DO NOT exclude cuz only '1' is in nodes
    {id: 'd', src: '6', target: '2'}, //DO NOT
    {id: 'e', src: '6', target: '8'}, //DO NOT
]

console.log(edges.filter(({src, target}) => !(nodes.includes(src) && nodes.includes(target))).map(({id})=>id));

如果nodes很大,则可以通过将其更改为 aSet而不是数组来显着提高效率。


推荐阅读