[英]How do I check if elements exist in an array using .some()?
I am trying to see if a particular pair of numbers exist in an array.我正在尝试查看数组中是否存在一对特定的数字。 I know that .some() works effectively when it's a simple array, but I can't seem to get it to work in nested arrays.
我知道 .some() 在它是一个简单数组时可以有效地工作,但我似乎无法让它在嵌套数组中工作。
Thank you in advance.先感谢您。
const array = [[1, 0], [2, 0], [3, 1], [4, 3], [5, 2]]; // checks whether an element exists const exists = (i) => i == [3, 1] || [1, 3]; console.log(array.some(exists)); // expected output: true
You need to check every value because of different arrays, you have different object references, and you misused the logical OR
operator.由于不同的数组,您有不同的对象引用,并且您误用了逻辑
OR
运算符,因此您需要检查每个值。 This does not include a comparison with another value.这不包括与另一个值的比较。
const array = [[1, 0], [2, 0], [3, 1], [4, 3], [5, 2]]; const exists = ([a, b]) => a === 3 && b === 1 || a === 1 && b === 3; console.log(array.some(exists));
Here is a general solution.这是一个通用的解决方案。
const array = [[1, 0], [2, 0], [3, 1], [4, 3], [5, 2]];
const expected = [[1, 3], [3, 1]];
const exists = (i) => expected.some((j) => {
return i.every((k, n) => j[n] === k);
});
console.log(array.some(exists));
This could be wrapped in a function to make it reusable.这可以包装在一个函数中以使其可重用。
const array = [[1, 0], [2, 0], [3, 1], [4, 3], [5, 2]];
const expected = [[1, 3], [3, 1]];
const containsAny = (array, expected) => {
return array.some((i) => expected.some((j) => {
return i.every((k, n) => j[n] === k);
}))
};
console.log(containsAny(array, expected));
You could make a custom function out of it which makes it reusable.您可以使用它制作自定义功能,使其可重用。 This is a simple example.
这是一个简单的例子。 By flattening the array you can check if values are the same.
通过展平数组,您可以检查值是否相同。
Got my inspiration on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some上得到我的灵感
const array = [[1, 0], [2, 0], [3, 1], [4, 3], [5, 2]]; const checkArrayFor = (needle, haystack) => { const flattenNeedle = needle.join(':'); const flattenArray = haystack.map(item => item.join(':')); return flattenArray.includes(flattenNeedle); }; console.log("Check for [1, 0]", checkArrayFor([1, 0], array)); console.log("Check for [1, 1]", checkArrayFor([1, 1], array));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.