Suman Verma Suman Verma - 2 months ago 12
Javascript Question

Merging complex 2D arrays into one

I am fetching a row from a table on UI.Below is just one row
Values from table UI on my console :

[ ' 0',
'ALPHA NUMERIC(100)\nPG_8_2670\nSt.Athens.,Pt\n1062645\nAutomation-if add row is editable\nALPHA NUMERIC(20)\nTIMESTAMP(19)\nYYYY-MM-DD(19)\n0' ]


Now i want to convert above result into below format.

[ ' 0','ALPHA NUMERIC(100)','PG_8_2670','St.Athens.,Pt','1062645','Automation-if add row is editable','ALPHA NUMERIC(20)','TIMESTAMP(19)','YYYY-MM-DD(19)','0' ]


Problem that i am actually facing is with comma which is present in
'St.Athens.,Pt'

I had written below code but that is not helping:

client.getText(obj.table.addedRow,function(err, values) {
console.log('VAlues before changes:',values);
var str = values.toString();
str = str.replace(/\n/g,",");
var values = str.split(',').toString();
console.log('Values from table of empty row post changes:',values);

Answer

Fundamentally it doesn't look like you need these lines

  str = str.replace(/\n/g,",");
  values = str.split(',').toString();

It may be far more effective to just split on the \n directly; thus

  values = str.split('\n');

You may want to manage the Array a little better though; something like a loop with a pop-push or loop-push combination should give you the required outcome.

Here's a complete working code sample:

var startArray = [ '  0',
  'ALPHA NUMERIC(100)\nPG_8_2670\nSt.Athens.,Pt\n1062645\nAutomation-if add row is editable\nALPHA NUMERIC(20)\nTIMESTAMP(19)\nYYYY-MM-DD(19)\n0' ];
var endArray = [];

startArray.forEach(function(key) { 
    if(key.indexOf("\n")>=0) {
        endArray = endArray.concat(key.split('\n'));
    } else {
        endArray.push(key);
    }
});

// voila, endArray contains 
// [ '  0','ALPHA NUMERIC(100)','PG_8_2670','St.Athens.,Pt','1062645','Automation-if add row is editable','ALPHA NUMERIC(20)','TIMESTAMP(19)','YYYY-MM-DD(19)','0' ]
Comments