Map an array of objects into a map, grouped by key js immutable object

I want to map an array of objects to output an immutable map that is grouped by a specific object.

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 the most efficient way to do this using immutablejs or seamlessly immutable?

im currently using abbreviation like:

array.reduce( (final,row) =>final.setIn(['byId',row.id],row) ,
              Immutable.Map({byId:{},byTime:{}});

this conclusion on indices as I want, but the problem with byTimeis that I need to combine, 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] :(
+4
source share
2 answers

You can get what you want 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>
Run codeHide result
+1

Javascript .

var data = [{ id: 1, time: 19072016 }, { id: 2, time: 19072016 }, { id: 3, time: 19072015 }, ],
    result = data.reduce(function (r, a) {
        r.byId[a.id] = a;
        r.byTime[a.time] = r.byTime[a.time] || [];
        r.byTime[a.time].push(a.id);
        return r;
    }, { byId: {}, byTime: {} });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hide result
0

Source: https://habr.com/ru/post/1656701/


All Articles