I have an array as follows:
"Totales": [
{
"Id": "1",
"Medio": "Datafono",
"diferenciaGr": 0.00,
"diferenciaML": 6000.00
},
{
"Id": "2",
"Medio": "Efectivo",
"diferenciaGr": 0.00,
"diferenciaML": 165000.00
},
{
"Id": "3",
"Medio": "Credito",
"diferenciaGr": 0.00,
"diferenciaML": 0.00
},
{
"Id": "4",
"Medio": "Transferencias",
"diferenciaGr": 0.00,
"diferenciaML": 0.00
}
I need to sum the last two fields: diferencaML and diferenciaGr.
For this, I am using reduce()
determinarBalance: function (balance) {
var cobranzasModel = this.getView().getModel("CobranzasSet"),
data = this.getView().getModel("CobranzasSet").getData();
let difML = data.Totales.reduce(function (dif, c) {
return dif + c.diferenciaML
})
let difGr = data.Totales.reduce(function (dif, c) {
return dif + c.diferenciaGr
})
console.log(difML);
console.log(difGr);
return (balance);
},
But for some reason both reduce functions are returning the following results:
[object Object]16500000
[object Object]000
Given the data above, the results should be 171000.00 and 0.00.
So, reduce it is not paying any attention to decimal point, plus adding [object Object] at the beginning. Any clues about this odd behaviour?
2
Answers
You need to set each reduce’s initial value to 0.
otherwise, it will use the first item itself (not just it’s .diferenciaML/.diferenciaGr) as the initial value, then converting everything to strings since you can’t add an object and a number (and then, you can’t add a string and number (without an implicit cast of the number to a string))
Some small annotations:
Wording:
In fact, you take the total of a single property, not the difference, which is not given and usually take by substraction from a value.
Syntax:
Array#reduce
takes either the first and second item of the array for the first iteration or only the first item along with an initialValue. By having properties, you need to start with value zero.Reusability:
By taking nearly the same code for getting a total value, you could hand over the property and get a total of all same named poperty of all objects in an array.