Creating different arrays with differents elements from one array

28 views
Skip to first unread message

Diego Mayorga

unread,
Nov 25, 2015, 8:48:41 PM11/25/15
to nodejs
Hi all, i'm trying to do this, I have an array that looks like this:

[ { rId: { id: '123455667' },
    form: 'layer',
    timeStamp: '2015-11-20T10:28:26-03:00',
    exa: '32144B5A0000200000000001' },
  { rId: { id: '123455667'},
    form: 'item',
    timeStamp: '2015-11-20T10:28:28-03:00',
    exa: '30142F13F0138D0000000057' },
  { rId: { id: '123455667' },
    format: 'item',
    timeStamp: '2015-11-20T10:28:27-03:00',
    exa: '30142F13F0138D0000000054' },
  { rId: { id: '123455667' },
    format: 'layer',
    timeStamp: '2015-11-20T10:29:09-03:00',
    exa: '32144B5A00002000000001AB' },
  { rId: { id: '123455667' },
    form: 'item',
    timeStamp: '2015-11-20T10:30:19-03:00',
    exa: '30142F13F0138D0000000055' } ]

And I want to create to separete arrayas that look likes:

[ { rId: { id: '123455667' },
    form: 'layer',
    timeStamp: '2015-11-20T10:28:26-03:00',
    exa: '32144B5A0000200000000001' },
    items: [
                { rId: { id: '123455667'},
                  form: 'item',
                  timeStamp: '2015-11-20T10:28:28-03:00',
                  exa: '30142F13F0138D0000000057' },
              { rId: { id: '123455667' },
                format: 'item',
                timeStamp: '2015-11-20T10:28:27-03:00',
                exa: '30142F13F0138D0000000054' }
            ]
]
 [ { rId: { id: '123455667' },
     format: 'layer',
     timeStamp: '2015-11-20T10:29:09-03:00',
     exa: '32144B5A00002000000001AB' },
     items: [
                 { rId: { id: '123455667' },
                   form: 'item',
                   timeStamp: '2015-11-20T10:30:19-03:00',
                  exa: '30142F13F0138D0000000055' } 
     ]
]

So in simple words, if there are two elements with format layer add elements with format item to the first element with format layer and those who are after the second layer to the second layer, and in the event that there is only one layer add all items formatted items to that layer

This may be silly but do not know where to start.

Thanks.

Zlatko

unread,
Nov 26, 2015, 6:20:13 PM11/26/15
to nodejs
Is all this information in MongoDB? Do you know about mapReduce? mapReduce would be your friend there.

Even if all this information is in-memory, a similar map-reduce approach could be done.

In essence:
- map phase - for all items, emit the entry in the above format (even with empty values where you don't have anything)
- reduce phase - take the items that have the same key ({rid: {id: '123'}} I guess in your case) - and merge the items arrays.

Except, you want two different layers - so you need two map-reduce runs, and map should be chained onto a filter (that makes sure you have either form or format).

Zlatko
Reply all
Reply to author
Forward
0 new messages