简体   繁体   中英

Sum Values of Object in a Array

trying to sum my values from my Object in my Array

I have 3 Objects and in every Object there are two fields where i have values declared:

let items = [
       {
        id: 1, 
        label: 'test', 
        itemname: 'testitem', 
        pieces: 4,
        weight: 0.02
      },
      {
        id: 2, 
        label: 'test', 
        itemname: 'testitem', 
        pieces: 4,
        weight: 0.02
      },
      {
        id: 2, 
        label: 'test', 
        itemname: 'testitem', 
        pieces: 4,
        weight: 0.02
      }
    ];

so if i am right the weight sum would be 0.06 and the sum of the pieces would be 12, both multiplied that would be 0.72, that means i want to multiply the sum of the weight with the sum of the pieces.

i saw examples like this:

const weight = items.reduce((prev, cur) => {
  return prev + (cur.weight * cur.pieces);
}, 0);
console.log(weight);

with this example the total sum would be only 0.24. Could someone help me here out

Edit: @Robby Cornelissen was right with his comment. It was a wrong way of thinking on my part.

If you want the total(sum) weight of all items, you will have to get the weight of each individual item first then add them all together.

const sum = (arr) => {
    return arr.map(item => item.pieces * item.weight).reduce((current, total) => current + total)
}

 let items = [{ id: 1, label: 'test', itemname: 'testitem', pieces: 4, weight: 0.02 }, { id: 2, label: 'test', itemname: 'testitem', pieces: 4, weight: 0.02 }, { id: 2, label: 'test', itemname: 'testitem', pieces: 4, weight: 0.02 } ] const sum = (arr) => { return arr.map(item => item.pieces * item.weight).reduce((current, total) => current + total) } const totalWeight = sum(items) console.log(totalWeight)

You can use forEach to loop through the array, adding up the pieces and weight values:

let pieces = 0; // sum of pieces
let weight = 0; // sum of weight
items.forEach(function(elmt){
    pieces += elmt.pieces;
    weight += elmt.weight;
});

Then multiply pieces * weight :

let total = pieces * weight;
console.log(total);

Using class

 let items=[{id:1,label:"test",itemname:"testitem",pieces:4,weight:.02},{id:2,label:"test",itemname:"testitem",pieces:4,weight:.02},{id:2,label:"test",itemname:"testitem",pieces:4,weight:.02}]; class total { weight = 0; pieces = 0; get product() { return this.weight * this.pieces; } } const totalObj = items.reduce((prev, cur) => { prev.weight += cur.weight; prev.pieces += cur.pieces; return prev; }, new total); console.log(totalObj.product);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM