如何使用分隔符将连接的数组拆分为多个块 [英] How to split joined array with delimiter into chunks
问题描述
我有一个字符串数组
const arr = ['some', 'word', 'anotherverylongword', 'word', 'yyy', 'u']
const joined = arr.join(';')
我想获取连接的字符串长度不大于10的大块数组
I want to get array of chunks where joined string length is not greater than 10
例如,输出为:
[
['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
]
推荐答案
您可以使用 传播语法
和
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);
这个想法是通过从 arr
的第一个元素( reduce
函数的第二个参数)开始,用块( result
)构建数组.),然后针对 arr
( arr.slice(1)
)的其余每个元素,检查是否可以将其附加到累加器( acc
).累加器最终成为分配给 result
的 reduce
的最终返回值.
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
.
这篇关于如何使用分隔符将连接的数组拆分为多个块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!