繁体   English   中英

检查每个id是否在数组中都有一个现有对象

[英]Check if every id has an existing object in array

我想检查数组的每个id是否都存在一个对象。

const ids = [ 'xxnQt5X8pfbcJMn6i', 'fbcJMn6ixxnQt5X8p' ]
const target = [
  { _id: 'xxnQt5X8pfbcJMn6i' },
  { _id: 'Qt5X8pfbcJMn6ixxn' },
]

在此示例中,我想获取false ,因为第二个ID(fbcJMn6ixxnQt5X8p)不存在。

这应该返回true

const ids = [ 'xxnQt5X8pfbcJMn6i', 'fbcJMn6ixxnQt5X8p' ]
const target = [
  { _id: 'xxnQt5X8pfbcJMn6i' },
  { _id: 'Qt5X8pfbcJMn6ixxn' },
  { _id: 'fbcJMn6ixxnQt5X8p' },
]

这是我尝试过的:

ids.every(id => target.find(element => element._id === id))

您已经很接近了,但是您需要传递一个函数而不是对象来find -如果您只想知道它是否存在,而不是需要该对象,我建议您使用some()而不是find作为回报。

 const ids = [ 'xxnQt5X8pfbcJMn6i', 'fbcJMn6ixxnQt5X8p' ] const target = [ { _id: 'xxnQt5X8pfbcJMn6i' }, { _id: 'Qt5X8pfbcJMn6ixxn' }, { _id: 'fbcJMn6ixxnQt5X8p' }, ] const allIn = ids.every(id => target.some(({_id}) => id === _id)); console.log(allIn); 

有很多条目,使用Set可能会更快(因此我们得到O(n + m)而不是O(n * m) ):

const idSet = new Set(target.map(el => el._id));
const result = ids.every(id => idSet.has(id));

由于每种方法本身都是检查器方法,因此它通过提供的函数返回truefalse 因此,您可以简单地返回false

const res = const res = ids.every(id => target._id === id); console.log(res);

true

const res = ids.every(id => target._id !== id); console.log(res);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM