由长度小于16的数组字符串组成

问题描述

我有这个数组["Brad","came","to","dinner","with","us"]

Brad came to dinner with us(27个字符> 16),因此我需要将其分成2个字符串:

Brad came to
dinner with us

无法切片单词

let inpt=["Brad","us"]
op=[]
for(i of inpt) if (op.join('').length+i.length <16) {op.push(i)} else break
console.log(op.join(' '))

这让我得到了第一部分,但是如果我的输入数组(字符串)长于16 + 16 + 16...。

解决方法

以空格连接后,使用正则表达式匹配最多16个字符,后跟一个空格或字符串的结尾:

let inpt=["Brad","came","to","dinner","with","us"];
const str = inpt.join(' ');
const matches = str.match(/.{1,16}(?: |$)/g);
console.log(matches);

,

也可以通过Array.reduce完成:

let inpt=["Brad","us"];

let out = inpt.reduce((acc,el) => {
  let l = acc.length;
  if (l === 0 || (acc[l - 1] + el).length > 15) {
    acc[l] = el;
  } else {
    acc[l - 1] += " " + el;
  }
  return acc;
},[]);

console.log(out);