如何将一个行数组组合成另一个数组,其中未标记的行与前一行合并



>我有一个多行注释,其中某些行有标签。

例如:

[
'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;
}

ree成一个数组,其键是标签,其值是该标签的关联字符串。如果在其中一个原始字符串中找不到标签,请将其添加到找到的上一个标签处的数组中:

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

如果你对正则表达式不满意,这里有一个没有它的函数(我用了列表而不是数组,但你抓住了漂移(......

    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;
    }
您可以使用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);

相关内容

  • 没有找到相关文章

最新更新