【问题标题】:How to get a value that never appear into specific property from the Array of objects如何从对象数组中获取永远不会出现在特定属性中的值
【发布时间】:2019-12-31 11:31:18
【问题描述】:

我有一个数组,其中包含一个对象列表,该列表具有两个属性 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]);

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

【问题讨论】:

  • find() 返回您在数组中找到的第一个对象。
  • 目标值总是串联的?并且应该是 1 到 n? all数组是如何创建的?
  • 目标值并不总是串联的。我关心的是在目标中从未出现的所有价值中找到价值。
  • 但是all value 是什么?
  • 我创建如下: let allC = new Array(); a.forEach(({ source, target }) => { allC.push(source); allC.push(target); }); console.log(new Set(allC));

标签: javascript arrays typescript ecmascript-6 ecmascript-5


【解决方案1】:

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

如果您想要更好的性能,请为 targets 使用 Set 而不是数组,因此您可以使用 .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)));

【讨论】:

  • 有没有办法不创建这个目标数组并使用现有的a数组
  • 只需遍历 a 并预先添加到每个集合中
猜你喜欢
  • 1970-01-01
  • 2011-05-27
  • 1970-01-01
  • 2021-04-03
  • 2019-12-27
  • 2018-11-05
  • 1970-01-01
  • 2023-02-26
  • 2015-04-05
相关资源
最近更新 更多