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 of strings into more arrays of strings?

Hello so what I want to do is split array of names into more arrays of names and each arrays element joined together should be smaller than specific amount of characters and none of the strings should be split in half. if it needs to be split in half then move it to the next array.
so an example would be.

Input: arr: ["george","ben","bob","alex","robert"] amount_of_characters: 10

Output: [["george","ben"],["bob","alex"],["robert"]]

>Solution :

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 arr = ["george","ben","bob","alex","robert"];
const amount_of_characters = 10;
const result = [];
let sumChars = 0;

for (let i = 0; i < arr.length; i++) {
  const word = arr[i];
  
  if (word.length + sumChars > amount_of_characters) {
    result.push([word])
    sumChars = 0;
  }
  else {
    !result.length ? result.push([word]) : result[result.length - 1].push(word);
  }
  
  sumChars += word.length;
};

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