Search code examples
javascriptcollectionsecmascript-6

ES6 group array objects by field type


Is there a terse es6 functional way to group items by type in that it's immutable?

accounts.json

   [
         {"account": {"name": "Bob's credit", "type": "credit", "id": "1"}},
         {"account": {"name": "savings", "type": "savings", "id": "2"}},
         {"account": {"name": "vacation savings", "type": "savings", "id": "3"}},
         {"account": {"name": "son's savings", "type": "savings", "id": "4"},
         {"account": {"name": "wife's credit card", "type": "savings", "id": "5"}
   ]

Expected

[
{"savings": [
    {"account": {"name": "savings", "type": "savings", "id": "2"}},
    {"account": {"name": "vacation savings", "type": "savings", "id": "3"}},
    {"account": {"name": "son's savings", "type": "savings", "id": "4"}
]},

{"checking": [
   {"account": {"name": "wife's credit card", "type": "savings", "id": "5"}
]

Solution

  • You can use Array#reduce to group your list by its elements inner type property :

    const data = [
         {"account": {"name": "Bob's credit", "type": "credit", "id": "1"}},
         {"account": {"name": "savings", "type": "savings", "id": "2"}},
         {"account": {"name": "vacation savings", "type": "savings", "id": "3"}},
         {"account": {"name": "son's savings", "type": "savings", "id": "4"}},
         {"account": {"name": "wife's credit card", "type": "savings", "id": "5"}}
    ];
    
    const res = data.reduce((acc, curr) => {
      if(!acc[curr.account.type]) acc[curr.account.type] = []; //If this type wasn't previously stored
      acc[curr.account.type].push(curr);
      return acc;
    },{});
    
    console.log(res);