Patrick Patrick - 7 months ago 13
Javascript Question

Array of Objects- Increment a column comparing with other column data

I have a very complex calculation at hand and i am finding it difficult to get it through. Here it is. I have a table.

Table 1: (Name, ID, Location and Sum are the columns of a table)

Name | ID | Location | Sum
rick | 1 | Gorets |
alex | 3 | hebrew |


Table 2: (City, ID, Sex are the columns of a table)

City | ID | Sex
wew | 34 | M
rfgf | 3 | F
dgff | 1 | M
hgfhg| 1 | F


Table 3: (Notice, ID, Flag are the columns of a table)

Notice | ID | Flag
hiji | 1 | true
asas | 1 | false


Final OUTPUT Needed for table 1 should be as follows.

Depending on the values of table 2 and table 3, table 1 should look like this

Name | ID | Location | Sum
rick | 1 | Gorets | 4
alex | 3 | hebrew | 1


I will explain you wat is the above thing i am tryin to achieve. As you can see, the first table column sum is empty. These gets updates based on the entries found in table2 and table3.

Basically. The 'ID' in table1 is searched in 'ID' of table2 and table3. for eg. ID with value '1' is searched in table2 and table3. It finds out that the ID is present 4 times in the 2nd and 3rd table. So it will put the sum value as 4.

Similarly it will search for 3 in the other 2 tables and finds out that it has occured only once, so it will update 1 in the 'sum' column for ID '3'.

I hope you have got what i am trying to achieve. If i do a console.log for the 3 tables data, this is the result

Table 1 :- console.log(userinfo);

[Object][Object]
[0-1]
[0]: Object
Name: 'rick'
ID: 1
Location:Gorets
Sum:
[1]: Object
Name: 'alex'
ID: 3
Location:hebrew
Sum:


Similar format of output for other 2 tables. Can someone please let me know how to update the Sum: with the calculation values mentioned above.

Answer

You could use an object which gets all counts of the ID in table 3 and as input for the count of table 2 and use it as lookup for assigning the sum in table 1.

function count(r, a) {
    r[a.ID] = (r[a.ID] || 0) + 1;
    return r;
}

var table1 = [{ Name: 'rick', ID: 1, Location: 'Gorets', Sum: undefined }, { Name: 'alex', ID: 3, Location: 'hebrew', Sum: undefined }, { Name: 'foo', ID: 42, Location: 'bar', Sum: undefined }],
    table2 = [{ City: 'wew', ID: 34, Sex: 'M' }, { City: 'rfgf', ID: 3, Sex: 'F' }, { City: 'dgff', ID: 1, Sex: 'M' }, { City: 'hgfhg', ID: 1, Sex: 'F' }],
    table3 = [{ Notice: 'hiji', ID: 1, Flag: true }, { Notice: 'asas', ID: 1, Flag: false }];

table1.forEach(function (a) {
    a.Sum = this[a.ID] || '-';
}, table2.reduce(count, table3.reduce(count, Object.create(null))));

document.write('<pre>' + JSON.stringify(table1, 0, 4) + '</pre>');