查看一个数组是否包含来自其他嵌套数组的JavaScript的所有数字? [英] See if an array contains all the number from other nested arrays with JavaScript?

查看:92
本文介绍了查看一个数组是否包含来自其他嵌套数组的JavaScript的所有数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为winingNumbers的数组。我需要测试其他数组(userOneNumers和userTwoNumers)以查看它们是否包含来自任何winingNumbers的嵌套数组的所有数字。

I have an array of arrays called winingNumbers. I need to test other arrays (userOneNumers and userTwoNumers) to see if they contain all of the numbers from any of winingNumbers's nested arrays.

const userOneNumers = [1,2,4,5];
const userTwoNumers = [1,2,3,6];

const winingNumbers = [
  [1,2,3],
  [4,5,6]
];

在此示例中,userOneNumers应返回false,但userTwoNumers应返回true。

In this example userOneNumers should return false but userTwoNumers should return true.

为了澄清,要返回true,数组必须包含1,2,3或4,5,6的全部。如果一个数组有两个例如1,2,4的数字,那么它应该返回false。

To clarify, to return true an array must contain ALL of either 1,2,3 or 4,5,6. If an array has some numbers from both eg 1,2,4 then it should return false.

此外,要测试的数组可能还有其他数字,例如8,9,1,2,3,7,但仍应返回true。

Also the array to be tested may have other numbers eg 8,9,1,2,3,7 but should still return true.

推荐答案

你可以拿一套并检查以前检查相同长度的数组。

You could take a set and check against with previously check same length of arrays.

function check(a, b) {
    var bb = new Set(b);
    return a.some(aa => aa.length === b.length && aa.every(aaa => bb.has(aaa)));
}


const userOneNumers = [1, 2, 4, 5];
const userTwoNumers = [1, 2, 3];
const winingNumbers = [[1, 2, 3], [4, 5, 6]];

console.log(check(winingNumbers, userOneNumers)); // false
console.log(check(winingNumbers, userTwoNumers)); // true

编辑问题后编辑,无需长度检查,只需针对给定值检查内部数组。

Edit after edit of the quesion, without length check, just check an inner array against the given values.

function check(a, b) {
    var bb = new Set(b);
    return a.some(aa => aa.every(aaa => bb.has(aaa)));
}


const userOneNumers = [1, 2, 4, 5];
const userTwoNumers = [1, 2, 3, 6];
const winingNumbers = [[1, 2, 3], [4, 5, 6]];

console.log(check(winingNumbers, userOneNumers)); // false
console.log(check(winingNumbers, userTwoNumers)); // true

这篇关于查看一个数组是否包含来自其他嵌套数组的JavaScript的所有数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆