首页 > 解决方案 > 您如何将一组行组合到另一个数组中,其中未标记的行与前一行组合?

问题描述

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

例如:

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

标签: javascriptarraysobject

解决方案


如果您对正则表达式不满意,这里有一个没有它的函数(我使用列表而不是数组,但您发现了偏差)...

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

推荐阅读