-1

I have an array of strings in javascript. I want to join the elements and create a single string. Now at a particular length, I want to divide the string (say in 3 parts) and create a new array with 3 elements.

firstArray = [
        'Hello, this is line one of the array sentence',
        'Hello, this is line two of the array sentance'
      ];
// Output - secondArray = ["Hello, this is line one of"," the array sentence Hello, this is","line two of the array sentance"]
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
Nishant soni
  • 41
  • 3
  • 9
  • So what is the rule on breaking it up into 3 parts? – epascarello Apr 13 '20 at 19:39
  • Is the output here what you're WANTING or what you're currently GETTING? At what string length are you wanting to split the strings? – technicallynick Apr 13 '20 at 19:46
  • As @epascarello asked, what is the rule? the pattern that the output should follow? If you need to do that just for the case in the example you can just hard code some conversions, but if you want to make it dynamically you need a rule. What would that be? – Berg_Durden Apr 13 '20 at 19:47
  • The op has specified "on a certain length", so I guess that will be the rule – Elias Faraone Apr 13 '20 at 20:01
  • Does this answer your question? [Split array into chunks](https://stackoverflow.com/questions/8495687/split-array-into-chunks) – Heretic Monkey Apr 13 '20 at 20:04

2 Answers2

0

You can use the match function:

    var firstArray = [
    "Hi this is a very very very long string, that",
    "is meant to be broken down every 10 or 15 characters"
    ];

    // First join the first array
    var joinedArray = firstArray.join("");

    // Split in chunks of 10
    var tenChunksArray = joinedArray.match(/.{1,10}/g);
    console.log(tenChunksArray);

    // Split in chunks of 15
    var fifteenChunksArray = joinedArray.match(/.{1,15}/g);
    console.log(fifteenChunksArray);
Elias Faraone
  • 266
  • 2
  • 7
0

You need to join your arrays into one, then divide it into digits and split into chunks. E.g.

const inputArr = [
  'Hello, this is line one of the array sentence',
  'Hello, this is line one of the array sentence',
];

const resplitArray = (arr, chunkSize) => {
  const res = [];
  const charsArr = arr.join(' ').split('');
  for (let i = 0, j = charsArr.length; i < j; i += chunkSize) {
    res.push(charsArr.slice(i, i + chunkSize).join(''));
  }
  return res;
};

console.log(resplitArray(inputArr, 10));

Update: I like the variant with regex match better

Dmitry Oleinik
  • 700
  • 1
  • 7
  • 20