我正在尝试有条件地拆分数组中的每个字符串。这是我的数组。
const categories = [
"Department of Natural Science",
"Department of public health and sanitation",
"Department of culture and heritage of state"
];
再次拆分每个字符串,我想将其更改为数组。该数组包含字符串的几个块。例如。通过分割Department of culture and heritage of state
字符串,我希望它分隔Department of
Natural
Science
。在这里,我想创建每个不同的块如果块包含超过13个字符长度的单词。这就是Natural
和Science
分开的原因,因为如果我们将它们的长度总和变为14。
这是我尝试过的。
const categories = [
"Department of Natural Science",
"Department of public health and sanitation",
"Department of culture and heritage of state"
];
const arrayOfAllString = []; // results at the end
categories.map(cur => {
// looping the array
const splitedItems = cur.trim().split(" "); // splitting the current string into words
const arrayOfSingleString = []; //
let str = "";
splitedItems.map(item => {
// looping the array of splitted words
if (str.length + item.length > 13) {
// trying to make a chunk
arrayOfSingleString.push(str);
str = ""; // clearing the str because it has been pushed to arrayOfSingleString
} else {
str = str.concat(item + " "); // concat the str with curent word
}
});
arrayOfAllString.push(arrayOfSingleString);
});
console.log(arrayOfAllString);
我的预期结果将是这样的:
arrayOfAllString = [
["Department of", "Natural", "Science"],
["Department of", "public health", "and", "sanitation"],
["Department of", "culture and", "heritage of", "state"]
];
进行了一些更改。1)清除时,更改为str = item;
而不是str = ''
2)循环结束,执行arrayOfSingleString.push(str);
添加最后一项。
const categories = [
"Department of Natural Science",
"Department of public health and sanitation",
"Department of culture and heritage of state"
];
const arrayOfAllString = []; // results at the end
var x = categories.map(cur => {
// looping the array
const splitedItems = cur.trim().split(" "); // splitting the current string into words
const arrayOfSingleString = []; //
let str = "";
splitedItems.forEach(item => {
// looping the array of splitted words
if (str.length + item.length > 13) {
// trying to make a chunk
arrayOfSingleString.push(str);
str = item; // clearing the str because it has been pushed to arrayOfSingleString
} else {
str = str.concat(item + " "); ; // concat the str with curent word
}
});
arrayOfSingleString.push(str);
arrayOfAllString.push(arrayOfSingleString);
return arrayOfSingleString;
});
console.log(x);
您可以使用生成器并以所需的长度返回块。
function* getJoined(string, size) {
var array = string.split(' '),
i = 0;
while (i < array.length) {
let s = array[i];
while (++i < array.length && (s + array[i]).length < size) {
s += ' ' + array[i];
}
yield s;
}
}
console.log([...getJoined('Department of culture and heritage of state', 13)]);