簡體   English   中英

如何檢查 Javascript 數組是否包含另一個數組的所有其他元素

[英]How do I check if a Javascript array contains all the other elements of another array

如果我有一個數組:

let x=  [0,1,2,3,5]

我有一個包含幾個子數組的數組:

let winningIndices = [[0, 1, 2], [6, 7, 8], [0, 3, 6], [2, 5, 8], [0, 4, 8], [2, 4, 6]]

如何檢查數組 x 是否包含任何一個子數組的所有元素。

換句話說,我如何檢查數組 x 是否具有數字 0、1、2 或 6、7、8 的組合...

提前致謝

“如何檢查數組 x 是否包含任何一個子數組的所有元素。”

這是最直接的功能解釋。

const won = winningIndices.some(indices=>
    indices.every(
        item=>x.includes(item)
    )
)

這可能是一種選擇。 如果您想從結果中刪除 xIncludesItem 鍵,只需再次 map 即可。

 const winningIndices = [ [0, 1, 2], [6, 7, 8], [0, 3, 6], [2, 5, 8], [0, 4, 8], [2, 4, 6] ]; const x = [0, 1, 2, 3, 5]; const result = winningIndices.map((item) => { const xIncludesItem = item.map((i) => x.includes(i)).every(includes => includes); return { item, xIncludesItem }; }).filter(result => result.xIncludesItem); console.log(result);

Array.includes 比Set.has慢得多。 基於 Ted Brownlow 的解決方案的性能稍高的解決方案是:

const setX = new Set(x);
const won = winningIndices.some(indices=>
    indices.every(
        item=>setX.has(item)
    )
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM