![](/img/trans.png)
[英]Reconstruct an array of objects in javascript that contains nested arrays
[英]See if an array contains all the number from other nested arrays with JavaScript?
我有一個數組,稱為winingNumbers。 我需要測試其他數組(userOneNumers和userTwoNumers)以查看它們是否包含所有winingNumbers嵌套數組中的所有數字。
const userOneNumers = [1,2,4,5];
const userTwoNumers = [1,2,3,6];
const winingNumbers = [
[1,2,3],
[4,5,6]
];
在此示例中,userOneNumers應該返回false,但是userTwoNumers應該返回true。
為了明確起見,要返回true,數組必須包含1,2,3或4,5,6的ALL。 如果一個數組有一些數字,例如1,2,4,那么它應該返回false。
同樣,要測試的數組可以具有其他數字,例如8,9,1,2,3,7,但仍應返回true。
您可以取一個集合並與以前檢查相同長度的數組進行比較。
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
在對問題進行編輯后進行編輯,而無需進行長度檢查,只需對照給定值檢查內部數組即可。
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.