1

I have an array of Objects:

const array = [ {
            "Type": "DefinedBenefitPension",
            "Description": null,
            "Year": 2016,
            "Participants": 9.0,
            "TotalAssets": 6668305.0,
            "NetAssets": 6668305.0,
            "PlanName": null
        },
        {
            "Type": "DefinedContributionPension",
            "Description": null,
            "Year": 2016,
            "Participants": 72.0,
            "TotalAssets": 17230395.0,
            "NetAssets": 17230395.0,
            "PlanName": null
        },
        {
            "Type": "DefinedBenefitPension",
            "Description": null,
            "Year": 2017,
            "Participants": 7.0,
            "TotalAssets": 2096999.0,
            "NetAssets": 2096999.0,
            "PlanName": null
        }...
    ];

This is just a small piece of data. There are a lot of different types (not only DefinedBenefitPension and DefinedContributionPension). I made an array with all unique types:

const uniquePensionTypes = data => {
    const unique = [...new Set(data.map(plan => plan.Type))];
    return unique;
};

Where I pass the original array as data. Now I need to divide Participants and TotalAssets as per same types. From this example I need to have arrays called definedBenefitPension

DefinedBenefitPensionParticipants = [9,7]
DefinedContributionPensionParticipants = [72]

How can I do that?

Robert
  • 2,603
  • 26
  • 25
Borislav Stefanov
  • 533
  • 3
  • 15
  • 38
  • what type of data you need. could you please add output as well – Sourabh Somani Feb 11 '20 at 14:39
  • Output that I need is added at the bottom "From this example I need to have arrays called definedBenefitPensionParticipants = [9,7] and DefinedContributionPensionParticipants = [72]" – Borislav Stefanov Feb 11 '20 at 14:43
  • Does this answer your question? [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) – AZ_ Feb 11 '20 at 15:17

1 Answers1

2

If data is the whole array of objects.

data.reduce( ( resObj, item ) => ({
  ...resObj,
  [ item.Type ]: [
    ...( resObj[ item.Type ] || [] ),
    item.Participants
  ]
}), {})

This will give you an object like

{
    DefinedBenefitPension:[9,7],
    DefinedContributionPension:[72]
}
Eric Hodonsky
  • 5,617
  • 4
  • 26
  • 36
stranded
  • 312
  • 2
  • 9