0

Given an array of objects representing a series of transactions i.e.

[{ person: 'a', sweets: 5 }, { person: 'b', sweets: 8 }, { person: 'a', sweets: 6 }]

How can I efficiently consolidate these records, to a total tally for each person i.e. :

[{ person: 'a', sweets: '11'}, { person: 'b', sweets: 8 }]

Is there some inbuilt function I donlt know about, or would I have to prototype one?

2
  • 1
    no there is no inbuilt function unless you are using a library like lodash or underscore. Not hard to do this yourself using a temporary object with person as keys Commented Oct 30, 2016 at 15:01
  • Have you tried anything so far? If so can you share your code? Commented Oct 30, 2016 at 15:22

2 Answers 2

2

You could use a hash table for grouping and summing.

var data = [{ person: 'a', sweets: 5 }, { person: 'b', sweets: 8 }, { person: 'a', sweets: 6 }],
    grouped = [];

data.forEach(function (a) {
    if (!this[a.person]) {
        this[a.person] = { person: a.person, sweets: 0 };
        grouped.push(this[a.person]);
    }
    this[a.person].sweets += a.sweets;
}, Object.create(null));

console.log(grouped);

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

Comments

0

There isn´t any built in function. You have to use two loops. Firstly you need to loop through the original array and for each iteration of that loop you need to loop through the final array to find the correct position to update. I would do something like this (I did not test this solution):

var arrayStart = [{ person: 'a', sweets: 5 }, { person: 'b', sweets: 8 }, { person: 'a', sweets: 6 }]
var arraySum = [];

arrayStart.forEach(function(valueStart, indexStart){
  var found = false;
  for(var i = 0; i < arraySum.length; i++){
    if(arraySum[i].person == valueStart.person){
      found = true;
      arraySum[i].sweets += valueStart.sweets;
      break;
    }
  } 
  if(!found){
    arraySum.push(valueStart);
  }
});

console.log(arraySum);

You can also use @NinaScholz solution, using an Hash-table prevents the second loop, basically it is more efficient.

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.