Search code examples
javascript

JavaScript reduce returning different values


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?


Solution

  • You need to set each reduce's initial value to 0.

    let difML = data.Totales.reduce(function (dif, c) {
        return dif + c.diferenciaML
    }, 0) // change is here
    let difGr = data.Totales.reduce(function (dif, c) {
        return dif + c.diferenciaGr
    }, 0) // change is here
    

    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))