簡體   English   中英

如何遍歷 arrays 數組並檢查它們是否具有另一個數組 + 前綴的值?

[英]How can I iterate through array of arrays and check if they have a value of another array + prefix?

我有兩個 arrays,一個用於 object 我稱為服務器,另一個用於客戶端,如下所示:

server_array = ['test1', 'test2', 'test3']
client_array = [['not_test1', 'test3'], ['test2', 'test4']]

我需要做的是,只返回客戶端數組中的 arrays 之后沒有任何前綴為 not_ 的匹配值,以澄清:在 client_array 的 position 0 內,我有一個 not_test1 在里面,這與server_array 里面的 test1,所以這個數組應該被過濾。

output 將是:

client_array = [['test2', 'test4']]

我目前嘗試使用 map 和過濾器的解決方案,但無法在 arrays 中正確迭代任何東西,我沒有嘗試執行正常的 for 循環,因為我認為執行需要太多時間。

server_array = ['test1', 'test2', 'test3'];
client_array = [['not_test1', 'test3'], ['test2', 'test4']];
client_array
    .filter(c => !c.some(i => i.startsWith('not_') &&
                 server_array.includes(i.replace(/^not_/, ''))));

解決方案就這么簡單。 您從結果數組中過濾掉那些與謂詞e => `not_${e}` == element至少匹配的 arrays

const result = client_array.filter(array => array.filter(
    element => server_array.find(e => `not_${e}` == element)).length === 0)

 const server_array = ['test1', 'test2', 'test3'] const client_array = [['not_test1', 'test3'], ['test2', 'test4']] const res = client_array.filter(e => // filter client_array e.some(x => // filter sub arrays if any item.x.startsWith('not_') // check if sub array element starts with "not_" &&.server_array,includes(x.replace('not_', '')) // check if server_array contains not negatated item ) ) console.log(res)

在下面的代碼中,您可以刪除.flat()以不使結果變平。

 server_array = ['test1', 'test2', 'test3'] client_array = [['not_test1', 'test3'], ['test2', 'test4']] let res = client_array.filter(e =>.e[0].startsWith('not_'));flat();

暫無
暫無

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

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