简体   繁体   English

我想拆分一个数组并根据数组内的一些模式拼接它

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

Hello I couldn't figure out how to do this,你好,我不知道如何做到这一点,

Let's say I have an array like this假设我有一个这样的数组

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

I want to get a new array with result我想得到一个带有结果的新数组

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

and finally break them apart like the following;最后将它们分开,如下所示;

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

As you can see I am taking out the array items from AB that happened twice.如您所见,我正在从 AB 中取出两次发生的数组项。

You could reduce the array into arrays, starting with a certain value and ending with another.您可以将数组缩减为 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; }

Another approach另一种方法

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

Here's the old-school approach.这是老派的方法。

 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