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

How to split an array into smaller arrays every time a specific value appears JavaScript?

How would you go about splitting an array at the word ‘split’ and creating smaller sub arrays out of them?

This is what my array looks like right now (but much longer):

const myArray = ['abc', 'xyz', 123, 'split', 'efg', 'hij', 456, 'split'];

This is what I would like it to look like:

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

const newArray =[['abc', 'xyz', 123], ['efg', 'hij', 456]];

If it helps at all I also have the indexes of the words ‘split’ in an array like this:

const splitIndex = [3, 7];

>Solution :

You could iterate splitIndex and slice the array until this index.

const
    data = ['abc', 'xyz', 123, 'split', 'efg', 'hij', 456, 'split'],
    splitIndex = [3, 7],
    result = [];

let i = 0;

for (const j of splitIndex) {
    result.push(data.slice(i, j));
    i = j + 1;
}

console.log(result);
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