10

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"}
]
chrisjlee
  • 21,691
  • 27
  • 82
  • 112

1 Answers1

32

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);
Zenoo
  • 12,670
  • 4
  • 45
  • 69