I want to sum a and b separately and divide their result by b/a .
{"a":10,"b":20,"c":29,"d":0},
{"a":25,"b":0,"c":9.13,"d":11},
{"a":0,"b":15.5,"c":86,"d":0},
{"a":21.2,"b":0,"c":34,"d":0}]
a=20 10 25 0 21 = 76
b=25.25 20 0 15.5 0 = 60.75
b/a = 60.75/76 = 0.799
CodePudding user response:
This should do it:
let elements =[{"a":10,"b":20,"c":29,"d":0},
{"a":25,"b":0,"c":9.13,"d":11},
{"a":0,"b":15.5,"c":86,"d":0},
{"a":21.2,"b":0,"c":34,"d":0}];
let result={}
for (let el of elements){
for (let k in el){
result[k]=(result[k]||0) el[k];
}
}
console.log(result.b / result.a)
CodePudding user response:
let ar = [
{"a":10,"b":20,"c":29,"d":0},
{"a":25,"b":0,"c":9.13,"d":11},
{"a":0,"b":15.5,"c":86,"d":0},
{"a":21.2,"b":0,"c":34,"d":0}
];
const ab = ar.reduce((s,c) => ({a: s.a c.a, b: s.b c.b}), {a: 0, b: 0});
console.log(ab.b / ab.a);
you can use reduce if you don't want to use external vars.
CodePudding user response:
Use map to go through the array of objects and sum the elements along the way.
let sumA;
let sumB;
Arr.map((i) => {
sumA = i.a;
sumB = i.b;
});
console.log(sumA)
console.log(sumB)
console.log(sumB/sumA)
CodePudding user response:
var obj = [{"a":10,"b":20,"c":29,"d":0},
{"a":25,"b":0,"c":9.13,"d":11},
{"a":0,"b":15.5,"c":86,"d":0},
{"a":21.2,"b":0,"c":34,"d":0}];
// better practice to use map/reduce
var sum = 0;
for (var i = 0; i < Object.values(obj).length; i ) {
sum = Object.values(obj)[i]["a"];
}
console.log('sum', sum);
var sum2 = 0;
for (var t = 0; t < Object.values(obj).length; t ) {
sum2 = Object.values(obj)[t]["b"];
}
console.log('sum2', sum2);
console.log('divided', sum / sum2);