javascript - 如何从 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));
解决方案
只需反转测试!
以删除元素,而不是在它们符合条件时保留它们。
而且我已经修复了你的解构参数列表的语法。
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
而不是数组来显着提高效率。
推荐阅读
- encoding - 如何在 Alembic 迁移中指定编码
- linux - 使用 SASL_SSL 创建 Kafka 源时出错:没有此类文件
- .net - 我可以在 Blazor 中运行需要大量内存的程序吗?
- python - 如何重组问卷回复
- python - 编译器显示 struct.error: ushort format requires 0 <= number <= (0x7fff * 2 + 1) in zipfile.py
- javascript - 从 HTML 响应中捕获文本并在节点 js 中写入条件
- flutter - Flutter Linux flutter: [MethodChannelFilePicker] 不支持的操作
- java - 如何模拟参数请求单元测试谷歌云功能?
- r - 不平衡数据的纵向多层次模型
- node.js - 如何从嵌套数组中获取字段和值并查询它们以在 mongodb 中查找 doc?