如何从对象数组中获取从未出现在特定 属性 中的值
How to get a value that never appear into specific property from the Array of objects
我有一个数组,其中包含具有两个属性 source
和 target
的对象列表。我想找到一个从未出现在 target
.
中的值
目前,我想出了一个非常奇怪的解决方案。根据提供的代码,我通过遍历 a
数组来创建两个单独的数组。 all
包含所有元素,targets
仅包含目标元素。然后我对其应用过滤器,它 return 就是答案。
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]);
我们是否有一些有效的解决方案,不需要创建这两个数组,我知道 return 元素只是一个。所以我不想得到一个数组作为答案
您可以使用.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)));
我有一个数组,其中包含具有两个属性 source
和 target
的对象列表。我想找到一个从未出现在 target
.
目前,我想出了一个非常奇怪的解决方案。根据提供的代码,我通过遍历 a
数组来创建两个单独的数组。 all
包含所有元素,targets
仅包含目标元素。然后我对其应用过滤器,它 return 就是答案。
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]);
我们是否有一些有效的解决方案,不需要创建这两个数组,我知道 return 元素只是一个。所以我不想得到一个数组作为答案
您可以使用.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)));