简体   繁体   English

检查数组中的所有用户是否至少有一个 ID 等于 ID 数组的元素?

[英]Check if all the users in an array have at least one element with an ID equal to an array of IDs?

The title is very hard to read, I get it.标题很难读,我明白了。

I have an array of objects with my users inside of it.我有一组对象,里面有我的用户。

const users = [{
  id: 0,
  name: "Test user 01",
}, {
  id: 1,
  name: "Test user 02"
}, {
  id: 3,
  name: "Test user 03"
}]

const idsToCheck = [2, 4]; 

I want a boolean True if at least one element of users have an ID equal to 2 OR to 4.如果至少一个用户元素的 ID 等于 2 或 4,我想要一个 boolean True。

I wanted to use Array.some but, with an array to check and not a single value, I cannot loop inside of the method without a lint error.我想使用Array.some但是,使用要检查的数组而不是单个值,我无法在没有 lint 错误的情况下在方法内部循环。

Thanks谢谢

Some does work.有些确实有效。

We are testing numeric IDs against an array of ints - there is reference equality between the IDs and the array elements so the includes is the shortest method over a double some我们正在针对整数数组测试数字 ID - ID 和数组元素之间存在引用相等性,因此包含是双精度数的最短方法

 const users = [{ id: 0, name: "Test user 01", }, { id: 1, name: "Test user 02" }, { id: 3, name: "Test user 03" }] const idsToCheck = [2, 4]; const bool = users.some(({id}) => idsToCheck.includes(id)) console.log(bool)

Does this looks OK to you?你觉得这还好吗?

 const users = [{ id: 0, name: "Test user 01", }, { id: 1, name: "Test user 02" }, { id: 3, name: "Test user 03" }] const idsToCheck = [2, 4]; const isPresent = users.some(user => idsToCheck.some(id => id === user.id)); console.log(isPresent)

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

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