Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 A-B that happened twice.

>Solution :

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;
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading