0

i want help on this. Thank you.

I have an object :

Funding : [
{person_id:'1';
Amount : '100'},

{person_id:'1';
Amount : '200'},

{person_id:'2';
Amount : '150'},

I would like to groupBy Funding by person_id and get the sum of Amount in each group. I use this code but nt working ..

  Groupe(array,key) {
      const result = {}
      array.forEach(funding => {
      if (!result[funding[person_id]]){
      result[funding[person_id]] = []
      }
      result[funding[person_id]].push(item)
       })
      return result
     }

2 Answers 2

1

I created two different examples, one a function will return the summed amount of just one of the keys. In the second, it will return the summed amount of all the keys.

Here is a codepen for that https://codepen.io/aquilesb/pen/BvbqMd

const data = [
{
  person_id:'1',
  amount : '100'},

{
  person_id:'2',
  amount : '150'
},
 {
  person_id:'1',
  amount : '150'
},
{
  person_id:'2',
  amount : '70'
}
];

const personID = '1';

// return by a key
const groupByKey = (list, key) => list.reduce((acc, item) => {
  if (item.person_id === key) {
    return parseInt(item.amount, 10) + acc;
  } 
  return acc;
}, 0);

//return the sum of all keys
const groupAll = list => list.reduce((acc, item) => {
  const accAmout = acc[item.person_id] || 0;
  return Object.assign({}, acc, {[item.person_id]: accAmout + parseInt(item.amount, 10)});
}, {});

console.log("groupByKey", groupByKey(data, personID));
console.log("groupAll", groupAll(data));

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

2 Comments

Thank you it working, but i can't merge results to vuejs objects. i tried this.results = groupbyKey; isn't working !
I create a codepen to show you how to use it: codepen.io/aquilesb/pen/wRZMxw
0

You can use lodash's .groupBy function and .reduce functions to group by Person ID first, and then add the amounts together. Using a computed property in Vue makes this very easy, and you can access the object in your template like its a regular property.

Vue/HTML Template

<div id="app">
  <ul v-for="(total,personId) in fundingByPerson">
    <li>Persond ID: {{personId}}, Amount : ${{total.toFixed(2)}}</li>
  </ul>
</div>

Javascript

// Include lodash via `npm install lodash`
import _ from 'lodash';

new Vue({
  el: "#app",
  data() {
    return {
      Funding: [
        {person_id:'1', Amount : '130'},
        {person_id:'1', Amount : '200'},
        {person_id:'2', Amount : '350'},
        {person_id:'45', Amount : '150'}
      ]
    }
  },
  computed: {
    // Group by Person, then add amounts together
    fundingByPerson: function(){
        let byPerson = _.groupBy(this.Funding, 'person_id');
        let totals = {};
        // Loop over each Group of Amounts, indexed by personId
        _.forEach(byPerson, function(amounts, personId){
            totals[personId] = _.reduce( byPerson[personId], function(sum, entry){
            return sum + parseFloat( entry.Amount );
        }, 0);

      })
      return totals;
    } // fundingByPerson
})

Here's a working fiddle: http://jsfiddle.net/mdy59c7e/6/

4 Comments

Thank you for your interest. In my case isn't working, maybe cuz i have a more complicated objet ? i dont have only person_id and amount .. ? I tried to debug, i have this error : "(error during evaluation)" , also i removed the sum function and still not working, the error is comming from byPerson
I apologize I wasn't clear. You need to install lodash and include it in the file. Let me edit my answer to clarify
can i insert grouby second argument as array?
@Franz I believe you can either group by an item key (as a string) or pass an "iteratee" function that will return a value based on that function. lodash.com/docs/4.17.15#groupBy

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.