How to split joined array with delimiter into chunks

user3075373 :

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
]
Alberto Trindade Tavares :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11844&siteId=1