问题
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