I have the following data (loaded by ajax):
[
{
"x": [1, 1, 2, 2, 2, 3, 3, 3, 4, 5],
"y": [3, 5, 4, 2, 5, 3, 4, 5, 1, 5],
"Value": [18, 15, 11, 12, 9, 2, 33, 12, 2, 4],
},
{
"x": [1, 1, 2, 2, 2, 3, 3, 3, 4, 5],
"y": [3, 5, 4, 2, 5, 3, 4, 5, 1, 5],
"Value": [16, 15, 11, 12, 9, 2, 33, 12, 2, 4],
},
{
"x": [1, 1, 2, 2, 2, 3, 3, 3, 4, 5],
"y": [3, 5, 4, 2, 5, 3, 4, 5, 1, 5],
"Value": [14, 15, 11, 12, 9, 2, 33, 12, 2, 4],
}
]
And I have a 5x5 table.
How can I calculate sum of each multiple element of "value" and put it in the table of right index?
My js code for now:
function risk(data) {
let sum = 0;
for (i = 0; i < data.length; i++) {
let b = data[i].Value;
console.log(b); // (10) [18, 15, 11, 12, 9, 2, 33, 12, 2, 4]
// (10) [16, 15, 11, 12, 9, 2, 33, 12, 2, 4]
// (10) [14, 15, 11, 12, 9, 2, 33, 12, 2, 4]
}
}
The end result must be like this:
You could take an object for collecting the values. For getting the result in back into the table, you could iterate the coordinates and get a value.
var data = [{ x: [1, 1, 2, 2, 2, 3, 3, 3, 4, 5], y: [3, 5, 4, 2, 5, 3, 4, 5, 1, 5], Value: [18, 15, 11, 12, 9, 2, 33, 12, 2, 4] }, { x: [1, 1, 2, 2, 2, 3, 3, 3, 4, 5], y: [3, 5, 4, 2, 5, 3, 4, 5, 1, 5], Value: [16, 15, 11, 12, 9, 2, 33, 12, 2, 4] }, { x: [1, 1, 2, 2, 2, 3, 3, 3, 4, 5], y: [3, 5, 4, 2, 5, 3, 4, 5, 1, 5], Value: [14, 15, 11, 12, 9, 2, 33, 12, 2, 4] }],
sum = data.reduce((r, {x, y, Value}) =>
(x.forEach((x, i) => {
r[x] = r[x] || {};
r[x][y[i]] = (r[x][y[i]] || 0) + Value[i];
}), r), {});
console.log(sum);