Как бы вы объединили массив строк в другой массив, где строки без меток объединяются с предыдущей строкой? - PullRequest
0 голосов
/ 12 июня 2019

У меня есть многострочный комментарий, в котором определенные строки имеют метки.

Например:

[
'Label1: this is the first line', 
'Label2: this is the second line', 
'this is the third line', 
'this is the fourth line', 
'Label3: this is the fifth line' ]

Я бы хотел сжать этот массив так, чтобы он распознавал, когда строка не имеет метки, к ней присоединяется последняя строка, которая имеет метку.

Желаемый результат:

[ 
'Label1: this is the first line', 
'Label2: this is the second line \n this is the third line \n this is the fourth line', 
'Label3: this is the fifth line' ]

Я пытаюсь выполнить двойной цикл, но он идентифицирует строки, которые просто не помечены текущим индексом.

else if (!isLineLabeled(lines[j+1], labels[i])){
}

function isLineLabeled(line, label) {
    return line.trim().toLowerCase().startsWith(label.toLowerCase());
}

function combineLines(lines) {
    let arr = [];
    const labels = ['Label1', 'Label2', 'Label3'];
    for (let i = 0; i < labels.length; i++) {
        for (let j = 0; j < lines.length; j++) {
            if (isLineLabeled(lines[j], labels[i])) {
                linesObj.push(lines[j]);
            }
        }
    }
    return arr;
}

Ответы [ 3 ]

0 голосов
/ 12 июня 2019

Если вы не знакомы с регулярным выражением, вот функция без него (я использовал списки вместо массивов, но вы уловили дрейф) ...

    public static List<string> GetLabelledList(List<string> list){
        var returnList = new List<string>();
        var currentString = string.Empty;
        foreach(var s in list){
            if(!s.StartsWith("Label")) {
                if(currentString != string.Empty){
                    currentString += " \n ";
                }
                currentString += s;
            }else{
                if(currentString != string.Empty){
                    returnList.Add(currentString);
                }
                currentString = s;
            }
        }
        if(currentString != string.Empty){
            returnList.Add(currentString);
        }
        return returnList;
    }
0 голосов
/ 13 июня 2019

Вы можете использовать Array.reduce для создания нового массива с вашим условием.

const arr = [
  'Label1: this is the first line',
  'Label2: this is the second line',
  'this is the third line',
  'this is the fourth line',
  'Label3: this is the fifth line'
];

const result = arr.reduce((result, currentItem) => {
  if (currentItem.startsWith('Label')) {
    result.push(currentItem);
  } else {
    result[result.length - 1] += ` ${currentItem}`;
  }
  return result;
}, []);

console.log(result);
0 голосов
/ 12 июня 2019

Сокращение до массива, ключи которого являются метками, а значения - связанной строкой этой метки.Если метка не найдена в одной из исходных строк, добавьте ее в массив с предыдущей найденной меткой:

const input = [
  'Label1: this is the first line',
  'Label2: this is the second line',
  'this is the third line',
  'this is the fourth line',
  'Label3: this is the fifth line'
];

let lastLabel;
const output = input.reduce((a, line) => {
  const labelMatch = line.match(/^([^:]+): ?(.*)/);
  if (!labelMatch) {
    a[a.length - 1] += `\n${line}`;
  } else {
    a.push(line);
  }
  return a;
}, []);
console.log(output);

Пример фрагмента только для строк с метками:

const input = ['Steps:', '1. one', '2. two', '3. three']

let lastLabel;
const output = input.reduce((a, line) => {
  const labelMatch = line.match(/^([^:]+): ?(.*)/);
  if (!labelMatch) {
    a[a.length - 1] += `\n${line}`;
  } else {
    a.push(line);
  }
  return a;
}, []);
console.log(output);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...