0

I have a requirement where i need to find sum the values of amt in different objects having same name. Below is the code snippet

traveler = [
  {  description: 'Senior', Amount: 50},
   {  description: 'Senior', Amount: 50},
   {  description: 'Adult', Amount: 75},
   {  description: 'Child', Amount: 35},
   {  description: 'Infant', Amount: 25 },
];

Here i want to caluclate the total sum of Amount in different objects with same description. eg: object 0 and 1 contains same description 'Senior' so the total amt is 100

How to achieve this in angular2?

Should i use inner forloops or is there any better approach? Please help me

Akhil Aravind
  • 5,741
  • 16
  • 35
coder12349
  • 437
  • 2
  • 12
  • 25
  • 2
    Possible duplicate of [Sorting an array of JavaScript objects](https://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects) – Heretic Monkey Jul 10 '18 at 13:59
  • 2
    if it is an array, then it has no written indices or if it is an object, then ith sould have curly brackets instead of square brackets. – Nina Scholz Jul 10 '18 at 14:00
  • `traveler ` doesn't seem like a valid array – BlackBeard Jul 10 '18 at 14:01
  • 1
    Please update your question to show what you have already tried, showcasing a **specific** problem you are facing in a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve). – palaѕн Jul 10 '18 at 14:02

6 Answers6

2

You could take a Map for collecting the values and render an array of objects with the grouped result.

var traveler = [{ description: 'Senior', amount: 50 }, { description: 'Senior', amount: 50 }, { description: 'Adult', amount: 75 }, { description: 'Child', amount: 35 },  { description: 'Infant', amount: 25 }],
    grouped = Array.from(
        traveler.reduce(
            (m, { description, amount }) => m.set(description, (m.get(description) || 0) + amount),
            new Map
        ).entries(),
        ([description, amount]) => ({ description, amount })
    );
    
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You can use reduce to group the array into an object.

let traveler = [{"description":"Senior","Amount":50},{"description":"Senior","Amount":50},{"description":"Adult","Amount":75},{"description":"Child","Amount":35},{"description":"Infant","Amount":25}]

let result = traveler.reduce((c, v) => {
  c[v.description] = (c[v.description] || 0) + v.Amount;
  return c;
}, {});

console.log(result);
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

I think you should use array#reduce method to do something like this perhaps:

let traveler = [
       {  description: 'Senior', Amount: 50},
       {  description: 'Senior', Amount: 50},
       {  description: 'Adult', Amount: 75},
       {  description: 'Child', Amount: 35},
       {  description: 'Infant', Amount: 25 },
    ];
    
function sumFinder(description) {
 return traveler.reduce((sum, e) => {
   (e.description == description) ? (sum += e.Amount) : (sum += 0)
   return sum;
 }, 0);
}

console.log(sumFinder('Senior'));
BlackBeard
  • 10,246
  • 7
  • 52
  • 62
0

Use Array.reduce() to get this output:

var traveler = [
   {  description: 'Senior', Amount: 50},
   {  description: 'Senior', Amount: 50},
   {  description: 'Adult', Amount: 75},
   {  description: 'Child', Amount: 35},
   {  description: 'Infant', Amount: 25 },
];
var res = traveler.reduce((acc, obj)=>{
  var existItem = acc.find(item => item.description === obj.description);
  if(existItem){
    existItem.Amount += obj.Amount;
    return acc;
  } 
  acc.push(obj);
  return acc;
}, []);
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

You can do it using rxjs among others:

travelers = [
      {  description: 'Senior', amount: 50},
      {  description: 'Senior', amount: 50},
      {  description: 'Adult', amount: 75},
      {  description: 'Child', amount: 35},
      {  description: 'Infant', amount: 25 }
    ];
//emit each person
const source = Rx.Observable.from(travelers);
//group by description
const example = source
  .groupBy(traveler => traveler.description)
  //return each item in group as array
  .mergeMap(group => group.toArray())
const reducer = (accumulator, currentValue) => {return accumulator + currentValue.amount};
const subscribe = example.subscribe(
  val => 
    console.log(
      {
        description: val[0].description, 
        amount: val.reduce( reducer, 0 )
      }
    )
);

This code's output is what you want:

[object Object] {
  amount: 100,
  description: "Senior"
}
[object Object] {
  amount: 75,
  description: "Adult"
}
[object Object] {
  amount: 35,
  description: "Child"
}
[object Object] {
  amount: 25,
  description: "Infant"
}

Finally, here is a JSBin you can play with: http://jsbin.com/kacoqulike/1/edit?js,console

Nikolas Kazepis
  • 111
  • 1
  • 8
0

A clean and simple solution with Array.prototype.reduce and ES6 Object assignment desctructuring:

const traveler = [{"description":"Senior","Amount":50},{"description":"Senior","Amount":50},{"description":"Adult","Amount":75},{"description":"Child","Amount":35},{"description":"Infant","Amount":25}]

const result = traveler.reduce((all, {description: d, Amount: a}) => {

    all[d] = (all[d] || 0) + a;
    return all;

}, {});

console.log(result);
Leonid Pyrlia
  • 1,594
  • 2
  • 11
  • 14