Javascript - Using reduce

Asked

Viewed 146 times

0

Good afternoon, folks! Are you all right? I hope so.

I’m starting my studies in Java Script, but I’m having difficulty implementing a function using reduce.

The code is as follows::

const cartasFrete = []

const sequencia = {
    _id: 0,
    get id() { return this._id++}
}

/*const getCartaFrete = (id) => {
    const aux = cartasFrete.filter((cartaFrete) => {
        return cartaFrete.id === id
    })
    return aux[0]
}
*/

const criarCartaFrete = (local, destino, valorFrete,porcentagem) => {
    return {
        id: sequencia.id,
        local: local,
        destino: destino,
        valorFrete: valorFrete,
        porcentagem: porcentagem,
        getValorFrete() {
            return this.valorFrete
        },

        getPorcentagem() {
            return this.porcentagem
        },
        getInformacoes() {
            return `
            Local: ${this.local}
            Destino: ${this.destino}
            Valor do Frete: ${this.valorFrete}
            Porcentagem: ${this.porcentagem * 100}
            `


        }
    }
}

const salvarCartaFrete = (...cartaFrete) => {
    cartaFrete.forEach((valor,indice) =>{
        cartasFrete[indice] = valor
    })
}

// ------------------------------------------------------ ## --------------------------------------------------//

let valoresCartas = []

const calcularCarta = (idCartaFrete, peso) => {
    const valorCarta = cartasFrete[idCartaFrete].getValorFrete()
    const valorTotal = valorCarta * peso
    const valorAbastecimento = valorTotal * cartasFrete[idCartaFrete].getPorcentagem()
    const valorTroco = valorTotal - valorAbastecimento
    return {
        total: valorTotal,
        troco: valorTroco,
        abastecimento: valorAbastecimento
    }

}

 const salvarCalculos = (...calculos) => {
    calculos.forEach((valor,indice) =>{
        valoresCartas[indice] = valor
    })
}

const calcularTodasCartas = (array) => {
    let valorGeral = array.reduce((acumulador,atual)=>{
        return acumulador + atual.total
    })
    return valorGeral
}

// ------------------------------------------------------ ## --------------------------------------------------//

salvarCartaFrete(
    criarCartaFrete('PMI','PEMA', 10.5, 0.5),
    criarCartaFrete('PMI','FILIAL', 14, 0.5),
    criarCartaFrete('SARZEDO','VDL', 22, 0.4)
)

salvarCalculos(
    calcularCarta(0,22),
    calcularCarta(1, 18),
    calcularCarta(2, 17)
)


console.log(valoresCartas)
console.log(calcularTodasCartas(valoresCartas))

The code works fine, until I use the function "compute" .

The idea of this function is to add the values of all Front Cards within the array "Values Cards".

Example:

In this code it generates the following array of objects:

[ { total: 231, troco: 115.5, abastecimento: 115.5 },
  { total: 252, troco: 126, abastecimento: 126 },
  { total: 374, troco: 224.4, abastecimento: 149.6 } ]

I want to take the values of the "total" keys of all array positions and add and return the accumulated value,

take the values of the keys "change".

Example:

Total: 231 + 252 + 374 = 857

Following this logic, I wrote the following code:

const calcularTodasCartas = (array) => {
        let valorGeral = array.reduce((acumulador,atual)=>{
            return acumulador + atual.total
        })
        return valorGeral
    }

But the result is this:

[object Object]252374

Could give me a light?

Thank you very much!

1 answer

2


Answer

Missed you set the initial value to 0:

let array = [
  { total: 231, troco: 115.5, abastecimento: 115.5 },
  { total: 252, troco: 126, abastecimento: 126 },
  { total: 374, troco: 224.4, abastecimento: 149.6 } 
]

const calcularTodasCartas = (array) => {
    let valorGeral = array.reduce((acumulador, atual)=>{
        return acumulador + atual.total
    }, 0) // faltou setar o valor inicial
    return valorGeral;
}

console.log(calcularTodasCartas(array));

So the first time it rotates, it will do (0 + { total: 231}), which results in 0 + 287, afterward (287 + { total: 252 }), which results in 287 + 252, on the third time 539 + { total: 374 }, which results in 539 + 374, and so on.

What went wrong?

In the previous way, you were adding up an object, in this case the acumulador with the value of the property atual.total, so I’d give that one up [object Object], when setting the initial value to 0, acumulador, become 0, as you can see in the example below:

let array = [
  { total: 231, troco: 115.5, abastecimento: 115.5 },
  { total: 252, troco: 126, abastecimento: 126 },
  { total: 374, troco: 224.4, abastecimento: 149.6 } 
]

// EXEMPLO SEM VALOR INICIAL
const calcularTodasCartasSemValorInicial = (array) => {
    let valorGeral = array.reduce((acumulador, atual)=>{
        console.log(acumulador);
        return acumulador + atual.total
    })
    return valorGeral;
}

// EXEMPLO COM VALOR INICIAL
const calcularTodasCartasComValorInicial = (array) => {
    let valorGeral = array.reduce((acumulador, atual)=>{
        console.log(acumulador);
        return acumulador + atual.total
    }, 0)
    return valorGeral;
}

console.log("Sem valor inicial: ", calcularTodasCartasSemValorInicial(array));
console.log("Com valor inicial: ", calcularTodasCartasComValorInicial(array));

  • It worked fine! I stayed for hours yesterday and couldn’t find the error kkkkk thank you very much!

  • You can even make the 3 sums in the same reduce, initiating the accumulator with {total: 0, troco: 0, abastecimento: 0} and adding so return {total: acumulador.total + atual.total, troco: acumulador.troco + atual.troco, abastecimento: acumulador.abastecimento + atual.abastecimento}

  • Really, but if I do it this way I don’t need to set the initial value as a parameter in reduce, right?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.