0

I need to group the records based on ID and display sum of weight. can someone please let me know the sum and group by method in Angular.

API Response:

data = [
  {Id:1, name: 'ABC', weight: 10 },
  {Id:1, name: 'ABC', weight: 14 },
  {Id:1, name: 'ABC', weight: 16 },
  {Id:2, name: 'DEF', weight: 23 },
  {Id:2, name: 'DEF', weight: 22 },
  {Id:4, name: 'GHI', weight: 44 },
  {Id:4, name: 'GHI', weight: 41 }
]

Expected output:

dataResult =  [
      {Id:1, name: 'ABC', weight: 40 },
      {Id:2, name: 'DEF', weight: 45 },
      {Id:4, name: 'GHI', weight: 85 }
    ]
1

2 Answers 2

2

You can use Array.reduce() to iterate over and Array.find() to find item by id. Then you can calculate the sum as followings:

const data = [
  {Id:1, name: 'ABC', weight: 10 },
  {Id:1, name: 'ABC', weight: 14 },
  {Id:1, name: 'ABC', weight: 16 },
  {Id:2, name: 'DEF', weight: 23 },
  {Id:2, name: 'DEF', weight: 22 },
  {Id:4, name: 'GHI', weight: 44 },
  {Id:4, name: 'GHI', weight: 41 }
]

const calculated = data.reduce((acc, item) => {
  
  let accItem = acc.find(ai => ai.Id === item.Id)
  
  if(accItem){
      accItem.weight += item.weight 
  }else{
     acc.push(item)
  }

  return acc;
},[])

console.log(calculated)

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

2 Comments

Thanks, your solution working for me. Is it possible to group based on two columns. In find can we use two columns?
You're welcome. Glad to hear it worked for you. Of course, you can expand the condition statement in find(): acc.find(ai => ai.Id === item.Id && ai.name === item.name) etc.
2

I wrote it in JavaScript, you can easily convert it to TypeScript.

data = [
  {Id:1, name: 'ABC', weight: 10 },
  {Id:1, name: 'ABC', weight: 14 },
  {Id:1, name: 'ABC', weight: 16 },
  {Id:2, name: 'DEF', weight: 23 },
  {Id:2, name: 'DEF', weight: 22 },
  {Id:4, name: 'GHI', weight: 44 },
  {Id:4, name: 'GHI', weight: 41 }
]

function entryIdAlreadyExists(dataEntries, entry) {
    for (let dataEntry of dataEntries) {
        if (entry.Id === dataEntry.Id) {
            return true;
        }
    }
    return false;
}

function updateWeightForEntryWithId (dataEntries, entry) {
    for (let dataEntry of dataEntries) {
        if (entry.Id === dataEntry.Id) {
            dataEntry.weight = dataEntry.weight + entry.weight;           
        }
    }
    return dataEntries;
}

let result = [];
for (let entry of data) {
    if (entryIdAlreadyExists(result, entry)) {
        result = updateWeightForEntryWithId (result, entry);
    } else {
        result.push(entry);
    }
}

console.log(result);

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.