How to split joined array with delimiter into chunks

痴心易碎 提交于 2021-02-18 16:34:53

问题


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
]

回答1:


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.



来源:https://stackoverflow.com/questions/60353704/how-to-split-joined-array-with-delimiter-into-chunks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!