首页 > 解决方案 > 如何从对象数组中获取永远不会出现在特定属性中的值

问题描述

我有一个数组,其中包含具有两个属性sourcetarget. 我想找到一个永远不会出现在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]);

我们是否有一些有效的解决方案,不需要创建这两个数组,我知道返回元素只有一个。所以我不想得到一个数组作为答案

标签: javascriptarraystypescriptecmascript-6ecmascript-5

解决方案


您可以使用.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)));


推荐阅读