Я пытаюсь условно разделить каждую строку в массиве. Это мой массив.
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"]
];