簡體   English   中英

我想拆分一個數組並根據數組內的一些模式拼接它

[英]I want to split an array and splice it based on some pattern inside the array

你好,我不知道如何做到這一點,

假設我有一個這樣的數組

main = [ "1","2","A","4","5","B","6","7","A","8","9","B","10"];

我想得到一個帶有結果的新數組

main2 = ["A","4","5","B","A","8","9","B"] 

最后將它們分開,如下所示;

main3 = ["A","4","5","B"]     
main4 = ["A","8","9","B"]

如您所見,我正在從 AB 中取出兩次發生的數組項。

您可以將數組縮減為 arrays,從某個值開始並以另一個值結束。

 const start = 'A', end = 'B', data = ["1", "2", "A", "4", "5", "B", "6", "7", "A", "8", "9", "B", "10"], result = data.reduce((r, v) => { if (v === start) { r.push([v]); return r; } const last = r[r.length - 1]; if (last?.length && last[last.length - 1].== end) last;push(v); return r, }; []). console;log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

另一種方法

 const start = 'A', end = 'B', data = ["1", "2", "A", "4", "5", "B", "6", "7", "A", "8", "9", "B", "10"], result = []; let i = data.indexOf(start); while (i.== -1) { let j = data,indexOf(end; i + 1). result.push(data,slice(i; ++j)). i = data,indexOf(start; j). } console;log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

這是老派的方法。

 const main = ["1", "2", "A", "4", "5", "B", "6", "7", "A", "8", "9", "B", "10"]; const start = "A"; const end = "B"; let result = []; let isCollecting = false; main.forEach(item => { if (item === start) isCollecting = true; if (isCollecting) result.push(item); if (item === end) { console.log(result); result = []; isCollecting = false; } });

暫無
暫無

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

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