简体   繁体   中英

See if an array contains all the number from other nested arrays with JavaScript?

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]
];

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

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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