Add data from array

Asked

Viewed 635 times

0

I have an array that data comes from the user’s filled form and make a map:

    dados.map(element=> {

  var x     
  var number1 = parseInt(element.preco),
      number2 = parseInt(element.peso)


      var tota = number1 * number2

      console.log(x += tota);             


  this.prod.push({
  produto: element.produto,
  peso: element.peso,
  preco: element.preco,
  total: element.preco * element.peso      
  })



})

And I wanted to know how to add up the total of all total of Array which is the preco * peso, I tried to do it that way x+=tota but he’s only adding the first two

  • Try to declare var x outside the dados.map(), and see if it works.

  • 1

    As the friend answered above, declares a variable outside of . map, example let allTotal, and within the map after the var tota = number1 * number2 you make a this.allTotal = this.allTotal + tota

  • I got it! obgg @rafaelmacedo

  • The price is in whole? There is the parseFloat() also

3 answers

2

see if this solution helps you:

    var dados = [{
        "produto": "arroz",
        "peso": "5",
        "preco": "15.90",
        "total": ""
    },
    {
        "produto": "feijão",
        "peso": "3",
        "preco": "5.90",
        "total": ""
    }];

    var new_dados = dados.map(item => {
        var r = parseInt(item.peso) * parseFloat(item.preco);
        item.total = r.toFixed(2);
        return item;
    });

    console.log(new_dados);

var total_geral = new_dados.reduce((prevVal, item) => { return prevVal + parseFloat(item.total) }, 0);

console.log('Total Geral: ',total_geral.toFixed(2));

  • i need to know the sum of all totals

  • @Maria, you need the price multiplied by the total and then the total of the array, is that it? I made the change in my same answer. If it is your solution, please mark as correct answer. ;)

1

Javascript has a function that solves your problem, it will add all the values and return you the final result

const total = dados.reduce((a, b) => (a.preco * a.peso) + (b.preco * b.peso), 0);
  • the result is coming out as Nan

  • Show me the input of your data please

1

Use the reduce function as code below;

Documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

  let dados = [
       {"peso":"1", "valor":"4"},
       {"peso":"2", "valor":"5"},
       {"peso":"3", "valor":"6"},
   ]
   produto = [] ;

   let total = dados.reduce((acumulado, corrente) =>{
        corrente.valor  =parseInt(corrente.valor);
        corrente.peso  =parseInt(corrente.peso);
        corrente.total = corrente.valor * corrente.peso;
        produto.push(corrente);

        return acumulado+corrente.total;
   
   },0);
   console.log(total);
   console.log(produto);

Browser other questions tagged

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