Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
Merge array fields together in JavaScript based on condition?

I have a string with this content that is split into an array:

var CLI = "STRING1 28 1.0\nSTRING2 26 0.5\nSTRING3 2 2.0\nSTRING4 5 1.0";
var CLIarr = CLI.toString().split("\n");
 CLIarr[i] = CLIarr[i].toString().split(" ");

The output can be generated like this:

for (i = count; i < CLIarr.length; i++) {
  console.log(CLIarr[i][0]+' '+CLIarr[i][1]+' '+CLIarr[i][2]+'\n');
}

Output:

STRING1 28  1.0
STRING2 26  0.5
STRING3 2   2.0
STRING4 5   1.0

How do I merge STRING3 and STRING4 together so that the output will look like this:

Info: 2+5=7 and (2.0+1.0)/2=1.5

STRING1 28  1.0
STRING2 26  0.5
MERGED  7   1.5

Info

The STRINGS in the CLI output may appear in another order. The CLI output may contain neither of both stings (STRING3, STRING4) or only STRING3 or only STRING4. If neither of both STRINGS are part of the CLI output, then then merge is not required. If only STRING3 or STRING4 are part of the CLI output they need to be simply rewritten into STRING5 and removed from the array afterwards.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You need to parse the number part of your string as int with parseInt() or float with parseFloat() to be able to do any math operations, because it's currently treated as string.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could filter the array of lines and add wanted lines.

const
    getMerged = ([a, b, count]) => count
        ? ['MERGED', a, b / count].join(' ')
        : [],
    CLI = "STRING1 28 1.0\nSTRING2 26 0.5\nSTRING3 2 2.0\nSTRING4 5 1.0",
    add = ['STRING3', 'STRING4'],
    merged = [0, 0, 0],
    result = CLI
        .split('\n')
        .filter(s => {
            const [type, a, b] = s.split(' ');
            if (!add.includes(type)) return true;
            merged[0] += +a;
            merged[1] += +b;
            merged[2]++;
        })
        .concat(getMerged(merged));

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Based on @Nina Scholz's fantastic work I've been able to create the final answer to my demand, that looks like this:

const
    getMerged = ([a, b, count]) => ['MERGED', a, (b / count).toFixed(1)].join(' '),
    CLI = "STRING1 28 1.0\nSTRING2 26 0.5\nSTRING3 2 2.0\nSTRING4 5 1.0",
    add = ['STRING3', 'STRING4'],
    merged = [0, 0, 0];
var
    result = CLI.split('\n').filter(s => {
            const [type, a, b] = s.split(' ');
            if (!add.includes(type)) return true;
            merged[0] += +a;
            merged[1] += +b;
            merged[2]++;
        });
if (merged[2] != 0) {
            result = result.concat(getMerged(merged));
    }

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda