1

I want to find sum of values in an array of objects with specific user and create a different array of objects with total value for the particular user.

This is the Array of objects that I have.

var userData = [
  {name: "user1", amount: 80},
  {name: "user1", amount: 12},
  {name: "user1", amount: 8},
  {name: "user2", amount: 60},
  {name: "user2", amount: 12},
  {name: "user3", amount: 90},
  {name: "user3", amount: 28}
]

The out put that I need.

UserGrandTotal = [
  {name: "user1", totalamount: 100},
  {name: "user2", totalamount: 72},
  {name: "user3", totalamount: 118}  
]
1

2 Answers 2

5

You could use reduce method for this by passing a callback provided function which is applied for every item in the array.

I created an hash structure using reduce where I stored every unique name as hash key and, as hash value, we have user details with total amount for that specified user.

As complexity of the algorithm, we have O(N) because we're iterating the whole array only once.

var userData = [ {name: "user1", amount: 80}, {name: "user1", amount: 12}, {name: "user1", amount: 8}, {name: "user2", amount: 60}, {name: "user2", amount: 12}, {name: "user3", amount: 90}, {name: "user3", amount: 28} ]; 

var result = Object.values(userData.reduce((hash, item) => {
    if (!hash[item.name]) {
        hash[item.name] = { name: item.name, amount: 0 };
    }
    hash[item.name].amount += item.amount;
    return hash;
}, {}));
console.log(result);

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

4 Comments

Out of curiosity, why do you use reduce and push the result to a separate variable instead of using a foreach?
@Thefourthbird, I updated my answer with a simple hash structure.
Yes, forEach could be another option, but using reduce we don't need to declare an optional variable result = [].
Also, with reduce we can use a shorter way with comma operator : var result = Object.values(userData.reduce((hash, item) => (!hash[item.name] ? (hash[item.name] = { name: item.name, amount: item.amount }) : (hash[item.name].amount += item.amount), hash), {}));
2

To give alternative answer using forEach and find:

var userData = [
  {name: "user1", amount: 80},
  {name: "user1", amount: 12},
  {name: "user1", amount: 8},
  {name: "user2", amount: 60},
  {name: "user2", amount: 12},
  {name: "user3", amount: 90},
  {name: "user3", amount: 28}
]

let userGrandTotal = [];

userData.forEach(user => {
  let grandUser = userGrandTotal.find(userGrand => userGrand.name === user.name);
  if(grandUser) {
    grandUser.amount += user.amount;
  }
  else {
    userGrandTotal.push(user)
  }
})

console.log(userGrandTotal)

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.