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

Split Array object into chucks

I have this array in JS

initialArray = [A,B,C,C,D,E,F,F,G,K]

I want to split into:

chucks = [[A,B,C], [C,D,E,F], [F,G,K]]

Duplicate items are separators such as ‘C’ or ‘F’

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

How to do this split in ES6?

>Solution :

Fairly straight forward solution using a single for loop and holding the current chunk in a variable to push to.

const initialArray = ['A', 'A', 'B', 'C', 'C', 'D', 'E', 'F', 'F', 'G', 'K', 'K'];

const chunk_at_duplicate = (arr) => {
  let chunk = [], res = [chunk];

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === arr[i - 1]) {
      res.push(chunk = []);
    }

    chunk.push(arr[i]);
  }

  return res;
};

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