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"}
]
The most efficient method to group by a key on an array of objects in js is to use the reduce function. The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
groupBy(dog => { return dog. breed; }); We can use the new groupBy function by calling it on the array instance, just like using a map , filter , or reduce function. groupBy takes a callback function which is called for each element in the array in ascending order.
An array is a homogeneous collection of values. It is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable.
Array Elements Can Be Objects JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With