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