Davide Davide - 6 months ago 9
Javascript Question

Parsing this table with Javascript into array of objects

i have this source table data.

Table source data

And i would get data parsed like this (grouped by row):

Table destination data

I grouped source table into an array of objects.
This is my array:

[ { rowId: 4, colId: 10 } { rowId: 4, colId: 11 } .... ]


Now i would get an array of parsed objects..

How can i do?
I parsed the array with a for loop but i got some error when i create the new array of objects..

My code:

for (var i=0; i<tableArray.length; i++) {

if (tableArray[i].rowId != rowLast) {
bar = true;
var row = tableArray[i].rowId;
var start = tableArray[i].colId;
}

if ((bar)&&(tableArray[i].colId != colLast)) {
var end = tableArray[i].colId;
tab = { row: row, start: start, end: end }
newTableArray.push(tab);
bar = false;
}


rowLast = tableArray[i].rowId;
colLast = tableArray[i].colId;

}


Help! I'm a bit confused in loop :(
Many thanks.

Answer

You could group the elements and use an object for the last values. This solution needs sorted data.

var array = [{ rowId: 4, colId: 10 }, { rowId: 4, colId: 11 }, { rowId: 4, colId: 12 }, { rowId: 4, colId: 20 }, { rowId: 4, colId: 21 }, { rowId: 6, colId: 6 }, { rowId: 6, colId: 7 }, { rowId: 6, colId: 8 }, { rowId: 7, colId: 12 }, ],
    group = [];

array.forEach(function (a, i) {
    if (!i ||                          // group changes if first object i = 0
        this.last.row !== a.rowId ||   //               or different rowId
        this.last.end + 1 !== a.colId  //               or not in sequence
    ) {
        this.last = { row: a.rowId, start: a.colId, end: a.colId };
        group.push(this.last);
    }
    this.last.end = a.colId;
}, {});

console.log(group);