Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split joined array with delimiter into chunks

I have array of strings

const arr = ['some', 'word', 'anotherverylongword', 'word', 'yyy', 'u']
const joined = arr.join(';')

I want to get array of chunks where joined string length is not greater than 10

for example output would be:

[
    ['some;word'], // joined string length not greater than 10
    ['anotherverylongword'], // string length greater than 10, so is separated
    ['word;yyy;u'] // joined string length is 10
]
like image 363
user3075373 Avatar asked Aug 04 '26 02:08

user3075373


1 Answers

You can use reduce (with some spread syntax and slice) to generate such chunks:

const arr = ['some', 'word', 'anotherverylongword', 'word', 'yyy', 'u'];
const chunkSize = 10;

const result = arr.slice(1).reduce(
  (acc, cur) =>
    acc[acc.length - 1].length + cur.length + 1 > chunkSize
      ? [...acc, cur]
      : [...acc.slice(0, -1), `${acc[acc.length - 1]};${cur}`],
  [arr[0]]
);

console.log(result);

The idea is building the array with the chunks (result) by starting with the first element from arr (second parameter to reduce function), and then, for each one of the remaining elements of arr (arr.slice(1)), checking if it can be appended to the the last element of the accumulator (acc). The accumulator ultimately becomes the final returning value of reduce, assigned to result.

like image 94
Alberto Trindade Tavares Avatar answered Aug 05 '26 15:08

Alberto Trindade Tavares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!