[英]See if an array contains all the number from other nested arrays with JavaScript?
I have an array of arrays called winingNumbers. 我有一个数组,称为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.
我需要测试其他数组(userOneNumers和userTwoNumers)以查看它们是否包含所有winingNumbers嵌套数组中的所有数字。
const userOneNumers = [1,2,4,5];
const userTwoNumers = [1,2,3,6];
const winingNumbers = [
[1,2,3],
[4,5,6]
];
In this example userOneNumers should return false but userTwoNumers should return true. 在此示例中,userOneNumers应该返回false,但是userTwoNumers应该返回true。
To clarify, to return true an array must contain ALL of either 1,2,3 or 4,5,6. 为了明确起见,要返回true,数组必须包含1,2,3或4,5,6的ALL。 If an array has some numbers from both eg 1,2,4 then it should return false.
如果一个数组有一些数字,例如1,2,4,那么它应该返回false。
Also the array to be tested may have other numbers eg 8,9,1,2,3,7 but should still return true. 同样,要测试的数组可以具有其他数字,例如8,9,1,2,3,7,但仍应返回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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.