1

I need a bit help to get the double count and total price for each person. My object

const obj = [
  {'name':'sven','price':'10'},
  {'name':'jan','price':'12'},
  {'name':'john','price':'5'},
  {'name':'nick','price':'13'},
  {'name':'sven','price':'11'},
  {'name':'jan','price':'7'},
  {'name':'nick','price':'9'},
];

From this object I am counting double from key 'name'. e.g. sven 2, jan 1, john 1, nick 2. I use this code for that

const counts = [];
obj.map((x)=>{ 
  counts[x[0]] = (counts[x[0]] || 0) + 1;
});

Now I need also the total count of key 'price' saves together with each person and I can't seem to find a way to do so.

result should be an array of object e.g.

counts = [
  {'person':'sven','count':'2','totalPrice':'21'},
  {'person':'jan','count':'2','totalPrice':'19'}
]

I know how to get double and I know how to count total, but not in the same loop and save as 1 object. If someone could help me a bit pointing the right direction please.

1 Answer 1

2

Here's an Array.reduce solution which checks whether the array contains an item with the same name property, and if so, increments its totalPrice property by the item's price property and its count property by 1.

const arr = [
  {'name':'sven','price':'10'},
  {'name':'jan','price':'12'},
  {'name':'john','price':'5'},
  {'name':'nick','price':'13'},
  {'name':'sven','price':'11'},
  {'name':'jan','price':'7'},
  {'name':'nick','price':'9'},
];

const result = arr.reduce((a, b) => {
  const found = a.find(e => e.name == b.name);
  if(found){
    found.totalPrice += +b.price;
    found.count++;
  }else{
    a.push({name:b.name, totalPrice: +b.price, count: 1})
  }
  return a
}, [])

console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.