Split an array into new arrays with character limit in each of the array

1

My problem is this:

I have the input string: "A|BB|CCC|DDDD|EEEEE|FFFFFF|GGGGGGG" . I need to split this string in the "|", so that in the case it divides in 6.

But I need each value to be in an array of 10 characters or more and the "|".

For example:

array(0) = "A|BB|CCC" //8 caracteres

array(1) = "DDDD|EEEEE" //10 caracteres

array(2) = "FFFFFF" //6 caracteres

array(3) = "GGGGGGG" //7 caracteres

As I've done so far:

  • I used split to break the input string;
  • I made a for the size of the array formed by the split;
  • I run each value of the array next to a counter in an if that puts the values concatenated with "|" inside the array.
asked by anonymous 24.10.2017 / 22:41

1 answer

1

I was able to do with the dividePartes function below. Click the blue Run button to test:

function dividePartes(s) {
    var partes = s.split("|");
    var resultado = [];
    var pedaco = "";

    for (var i = 0; i < partes.length; i++) {
        var adicionando = pedaco;
        if (adicionando === "") {
            adicionando = partes[i];
        } else {
            adicionando += "|" + partes[i];
        }
        if (adicionando.length <= 10) {
            pedaco = adicionando;
        } else {
            resultado.push(pedaco);
            pedaco = partes[i];
        }
    }
    resultado.push(pedaco);
    return resultado;
}

var a = "A|BB|CCC|DDDD|EEEEE|FFFFFF|GGGGGGG";
document.write(JSON.stringify(dividePartes(a)));

var b = "A|BB|CCC|DDDD|EE|FFF|GG|HH|I|J|KKKKKKKKKKKK|LL|MM|NN";
document.write(JSON.stringify(dividePartes(b)));
    
24.10.2017 / 22:59