1
const array = [ 
    {address:'12312',vid:'1',amt:'0.1'},
    {address:'12312',vid:'1',amt:'0.1'},
    {address:'12312',vid:'2',amt:'0.1'},
];

the result I want is [{address:'12312',vid:'1',amt:'0.2'},{address:'12312',vid:'',amt:'0.1'}]

var totalAmt = 0;
var count = 0;
var vid = []
var result = [];
array.forEach(element => {
    if(!vid.includes(element.vid)){
        totalAmt = totalAmt + Number(element.amt); 
        vid.push({vid:element.vid,total:totalAmt});     
    }else {
        console.log("lakalaka");
        // totalAmt = totalAmt + Number(element.amt);
    }
});
console.log(totalAmt,vid);

Need to calculate sum of amt of an array of objects but when vid is not same it should push that into new array as an object thanks in advance.

Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68
Krishna
  • 53
  • 5
  • Do you _really_ want `vid:''` in your result for what was `2` in your input data? – CBroe Feb 23 '23 at 13:51
  • `vid.includes(element.vid)` - that should never be true. Your items in vids are these objects, but you are trying to compare them with a scalar value here. – CBroe Feb 23 '23 at 13:52

1 Answers1

2

One solution is to group the items with vid and then sum amt of each group items.

const array = [{
    address: '12312',
    vid: '1',
    amt: '0.1'
  },
  {
    address: '12312',
    vid: '1',
    amt: '0.1'
  },
  {
    address: '12312',
    vid: '2',
    amt: '0.1'
  },
];

const groups = array.reduce((groups, item) => ({
  ...groups,
  [item.vid]: [...(groups[item.vid] || []), item]
}), {});


const result = Object.values(groups).map(group => group.reduce((acc, item, index) => {
  return {
    ...acc,
    amt: +acc.amt + +item.amt
  }
}))

console.log(result)

Source of group function

Mina
  • 14,386
  • 3
  • 13
  • 26