JavaScript在另一个数组中查找嵌套数组

发布于 2025-01-17 12:46:10 字数 196 浏览 1 评论 0 原文

我有一个数组

a = [ [1,2],[3,4] ]

b = [1,2]

,我想查找 b 是否在 a 中,我该怎么做?

我尝试使用

a.includes(b) 

or

a.find(e => e == b)

但两者都不起作用

I have an array

a = [ [1,2],[3,4] ]

b = [1,2]

I want to find if b is in a, how would i do that?

I tried using

a.includes(b) 

or

a.find(e => e == b)

but both don't work

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

长亭外,古道边 2025-01-24 12:46:10

<代码>一些 。如果内部阵列的长度与 b 的长度不匹配,请立即返回false,否则使用 检查内部阵列 incover b 。这也将检查何时 [2,1] 等元素何时出现。

const a = [ [ 1, 2 ], [ 3, 4 ] ];
const b = [ 1, 2 ];
const c = [ 1, 2, 3 ];
const d = [ 3 ];
const e = [ 3, 4 ];
const f = [ 2, 1 ];

function check(a, b) {
  return a.some(arr => {
    if (arr.length !== b.length) return false;
    return b.every(el => arr.includes(el));
  });
}

console.log(check(a, b));
console.log(check(a, c));
console.log(check(a, d));
console.log(check(a, e));
console.log(check(a, f));

Iterate over a with some. If the length of the inner array doesn't match the length of b immediately return false, otherwise use every to check that the inner array includes all of the elements of b. This will also check when elements are out of order like [2, 1] should you need to do so.

const a = [ [ 1, 2 ], [ 3, 4 ] ];
const b = [ 1, 2 ];
const c = [ 1, 2, 3 ];
const d = [ 3 ];
const e = [ 3, 4 ];
const f = [ 2, 1 ];

function check(a, b) {
  return a.some(arr => {
    if (arr.length !== b.length) return false;
    return b.every(el => arr.includes(el));
  });
}

console.log(check(a, b));
console.log(check(a, c));
console.log(check(a, d));
console.log(check(a, e));
console.log(check(a, f));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文