javascript - 如何从对象数组中获取永远不会出现在特定属性中的值
问题描述
我有一个数组,其中包含具有两个属性source
和target
. 我想找到一个永远不会出现在target
.
目前,我想出了一个非常奇怪的解决方案。根据提供的代码,我通过遍历一个数组来创建两个单独的a
数组。all
包含所有元素且targets
仅包含目标元素。然后我对其应用过滤器并返回答案。
const a = [
{ source: '2', target: '3' },
{ source: '1', target: '2' },
{ source: '3', target: '4' },
{ source: '4', target: '5' }
];
const all = ['1', '2', '3', '4', '5'];
const targets = ['3', '2', '4', '5'];
console.log(all.filter(e => !targets.includes(e))[0]);
我们是否有一些有效的解决方案,不需要创建这两个数组,我知道返回元素只有一个。所以我不想得到一个数组作为答案
解决方案
您可以使用.find
来查找第一个匹配元素:
const a = [
{ source: '2', target: '3' },
{ source: '1', target: '2' },
{ source: '3', target: '4' },
{ source: '4', target: '5' }
];
const sources = [];
const targets = [];
a.forEach(({ source, target }) => {
sources.push(source);
targets.push(target);
});
console.log(sources.find(e => !targets.includes(e)));
如果您想要更好的性能,请为 使用 Set 而不是数组targets
,因此您可以使用.has
而不是.includes
(导致整体复杂性为O(n)
而不是O(n^2)
):
const a = [
{ source: '2', target: '3' },
{ source: '1', target: '2' },
{ source: '3', target: '4' },
{ source: '4', target: '5' }
];
const sources = [];
const targets = new Set();
a.forEach(({ source, target }) => {
sources.push(source);
targets.add(target);
});
console.log(sources.find(e => !targets.has(e)));
推荐阅读
- php - Android JSON POST 方法
- python - AttributeError:模块'inspect'没有使用Textmate的属性'getsource'
- spring-security-oauth2 - Azure AD B2C 是否为每个注册或登录策略提供一个端点,例如来自 OIDC 的 user-info-uri?
- python - 尝试使用 read_csv w/to_sql 将行附加到 SQL 表时,由于列中的额外逗号导致 Pandas 解析错误
- c - 为什么涉及变量的操作在C中不会溢出
- javascript - JQuery在查询结果中获取元素的父级
- html - 无法在 Bootstrap 4 中的品牌名称旁边的导航中证明内容的合理性
- graphql - GatsbyJS 如何推断 GraphQL 数据类型?
- java - 无法加载身份验证插件“caching_sha2_password”。即使 mysql-connector 是最新的
- python - 如何从具有多个类别/子类别的网站上抓取(网络抓取)所有产品?