i want to map an array of object to output Immutable Map that is grouped by specific object key.
array looks like
[
{id:1, time:19072016},
{id:2, time:19072016},
{id:3, time:19072015},
]
output im seeking is
[
byId: {
1:{id:1, time:19072016},
2:{id:2, time:19072016},
3:{id:3, time:19072015},
},
byTime: {
19072016:[1,2],
19072015:[3],
}
]
what is most effective way to do it using immutablejs or seamless-immutable ?
currently im using reduce as :
array.reduce( (final,row) =>final.setIn(['byId',row.id],row) ,
Immutable.Map({byId:{},byTime:{}});
this output byIds as i want it, but problem with byTime
is that i need to merge not overwrite.
i tried with seamless-immutable i did:
Seamless(arr).toObject(i=>[i.id,i]) //this will return byId as i want it
Seamless(arr).toObject(i=>[i.time,[i.id]]) //this will not merge [1,2] :(
You can get what you want by using .groupBy()
and .map()
.
const data = Immutable.fromJS([
{id:1, time:19072016},
{id:2, time:19072016},
{id:3, time:19072015},
]);
const byId = data
.groupBy(item => item.get('id'))
.map(items => items.first());
console.log(byId);
const byTime = data
.groupBy(item => item.get('time'))
.map(items => items.map(item => item.get('id')));
console.log(byTime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>
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