如何将带分隔符的连接数组拆分成块
How to split joined array with delimiter into chunks
我有字符串数组
const arr = ['some', 'word', 'anotherverylongword', 'word', 'yyy', 'u']
const joined = arr.join(';')
我想获取连接字符串长度不大于 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
]
您可以使用reduce
(with some spread syntax
and slice
)生成这样的块:
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
)。累加器最终成为reduce
的最终返回值,赋值给result
.
我有字符串数组
const arr = ['some', 'word', 'anotherverylongword', 'word', 'yyy', 'u']
const joined = arr.join(';')
我想获取连接字符串长度不大于 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
]
您可以使用reduce
(with some spread syntax
and slice
)生成这样的块:
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
)。累加器最终成为reduce
的最终返回值,赋值给result
.