Skip to content Skip to sidebar Skip to footer

Javascript - Sum The Values Of Same Ids Of Different Objects In The Array Of Objects

I have an array of objects in my code. The objects are having same keys with different or same values. var a = []; a.push({taxid : 1, tax_name: 'VAT', tax_value:'25

Solution 1:

You can just use reduce and sum the values together

var a = [];
a.push({taxid : 1, tax_name: 'VAT', tax_value:'25.00'});
a.push({taxid : 2, tax_name: 'Service Tax', tax_value:'20.00'});
a.push({taxid : 1, tax_name: 'VAT', tax_value:'25.00'});
a.push({taxid : 2, tax_name: 'Service Tax', tax_value:'75.00'});

let res = a.reduce((a, b) =>
  a.set(b.taxid, (a.get(b.taxid) || 0) + Number(b.tax_value)), newMap);

console.log(res);

If you want to get the resulting Map to an object, you can use

toObject(map) {
    let obj = Object.create(null);
    for (let [key, value] of map.entries()) {
        obj[key] = value;
    }
    return obj;
} 

console.log(toObject(res));

Solution 2:

you can achive this in different ways.

One ay is to use reduce:

a = a.reduce((c, i)=>{c[i.taxid]=(c[i.taxid]||0)+parseFloat(i.tax_value); returnc},{});

is this is too complecated for you, you can use a loop:

var t = {};
a.forEach((v)=>t[v.taxid]=(t[v.taxid]||0)+parseFloat(v.tax_value));
a = t;

of if the expression is too complecated, you can achive this with a simple if condition:

var t = {};
a.forEach((v)=>{
  if(t[v.taxid])
    t[v.taxid]+=parseFloat(v.tax_value);
  else
    t[v.taxid] = parseFloat(v.tax_value);
});
a = t;

EDIT: In response to the edit of the question and the volitionaly output: [{taxid : NUM, tax_value : NUM}, ...]

a = a.reduce((c, i)=>{
  let cc = c.findIndex((e)=>e.taxid==i.taxid);
  if(cc==-1) c.push({taxid: i.taxid, tax_value: parseFloat(i.tax_value)});
  else c[cc].tax_value += parseFloat(i.tax_value)
  return c
}, []);

Solution 3:

var output = a.reduce( (final,data) => {
 let isAlready = final.find( ( value ) => { 
   value.taxid == data.taxid;
 });
 if(!isAlready){
   final.push( data );
 } else {
   var index = final.indexOf(isAlready);
   final[index].tax_value = parseFloat(final[index].tax_value) + parseFloat(data.tax_value);
 }
 returnfinal;
},[] )

Solution 4:

Some considerations:

  • tax_value is a string. You need at least an implicit type casting to number, because if you add a number and a string, the number gets converted to string and you get a string concatination, but not an arithmetic operation.

  • Mutate the given data structure or create a new one. In this case and usually always, it is better to generate a new result set instead of using the given structure as data and as result set. This may lead to confusion, because some code may relay on unchanged structures.

Solution

  • Using a hash table, which might be a Map on newer systems (ES6) or an object for keeping reference to the same object with the same taxid.

  • Using an implicid conversion to number with an unary plus +.

  • Using a single loop.

var data = [{ taxid: 1, tax_name: 'VAT', tax_value:' 25.00' }, { taxid: 2, tax_name: 'Service Tax', tax_value: '20.00' }, { taxid: 1, tax_name: 'VAT', tax_value: '25.00' }, { taxid: 2, tax_name: 'Service Tax', tax_value: '75.00' }],
    hash = Object.create(null),
    result = [];

data.forEach(function (o) {
    if (!hash[o.taxid]) {
        hash[o.taxid] = { taxid: o.taxid, tax_name: o.tax_name, tax_value: 0 };
        result.push(hash[o.taxid]);
    }
    hash[o.taxid].tax_value += +o.tax_value;
});

console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Solution 5:

**You can do it using forEach loop by creating empty object and start initializing it in each iteration it will check for the taxid if found then it will add to it otherwise it will go to else **

const a = [];
    a.push({taxid : 1, tax_name: 'VAT', tax_value:'25.00'});
    a.push({taxid : 2, tax_name: 'Service Tax', tax_value:'20.00'});
    a.push({taxid : 1, tax_name: 'VAT', tax_value:'25.00'});
    a.push({taxid : 2, tax_name: 'Service Tax', tax_value:'7.00'});    
    a.push({taxid : 3, tax_name: 'Service Tax', tax_value:'3.00'});

    let holders={};
    a.forEach(function (item) {
          if (holders.hasOwnProperty(item.taxid)) {
            holders[item.taxid] = holders[item.taxid] + parseFloat(item.tax_value);
          } else {
            holders[item.taxid] = parseFloat(item.tax_value);
          }
        });
        console.log(holders);

Post a Comment for "Javascript - Sum The Values Of Same Ids Of Different Objects In The Array Of Objects"