Условно разбитый и сжатый текст - PullRequest
2 голосов
/ 29 января 2020

Я пытаюсь условно разделить каждую строку в массиве. Это мой массив.

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"]
];

Ответы [ 2 ]

2 голосов
/ 29 января 2020

Вы можете взять генератор и вернуть куски нужной длины.

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)]);

Класси c подход без промахов map.

function getJoined(string) {
    var array = string.split(' '),
        size = 13,
        i = 0,
        result = [];

    while (i < array.length) {
        let s = array[i];
        while (++i < array.length && (s + array[i]).length < size) {
            s += ' ' + array[i];
        }
        result.push(s);
    }
    return result;
}

const categories = ["Department of Natural Science", "Department of public health and sanitation", "Department of culture and heritage of state"];

console.log(categories.map(getJoined));
.as-console-wrapper { max-height: 100% !important; top: 0; }
1 голос
/ 29 января 2020

Сделано несколько изменений. 1) во время очистки измените на str = item; вместо str = '' 2) Конец l oop, сделайте arrayOfSingleString.push(str); для добавления последнего элемента.

const categories = [
  "Department of Natural Science",
  "Department of public health and sanitation",
  "Department of culture and heritage of state"
];

const arrayOfAllString = categories.map(cur => {
  const splitedItems = cur.trim().split(" ");

  const arrayOfSingleString = [];
  let str = "";
  while (splitedItems.length > 0) {
    const item = splitedItems.shift();
    if (str.length + item.length >= 13) {
      // trying to make a chunk
      arrayOfSingleString.push(str);
      // clearing the str because it has been pushed to arrayOfSingleString
      str = item;
    } else {
      // concat the str with curent word
      str = str ? `${str} ${item}` : item;
    }
  }
  arrayOfSingleString.push(str);
  return arrayOfSingleString;
});

console.log(arrayOfAllString);
...