Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looping over array of object

I have an array of objects, trying to create a new array

 a=[
    {
        sessionID: '1',
        timestamp: '2022-06-26T05:47:00.794Z',
        taskName: 'abc'
    },
    {
        sessionID: '1',
        timestamp: '2022-06-26T05:47:21.626Z',
        taskName: 'def'
    },
    {
        sessionID: '1',
        timestamp: '2022-06-26T05:47:21.626Z',
        taskName: 'ghi'
    },
    {
        sessionID: '1',
        timestamp: '2022-06-26T05:47:21.626Z',
        taskName: 'jkl'
    },
    {
        sessionID: '2',
        timestamp: '2022-06-26T11:01:48.499Z',
        taskName: '123'
    },
    {
        sessionID: '2',
        timestamp: '2022-06-26T11:28:07.389Z',
        taskName: '456'
    }
]

trying to create a new array based on session ID
[abc<<def<<ghi<<jkl,123<<456]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

lets group array of objects by something using reduce method.

var a = [{sessionID:"1",timestamp:"2022-06-26T05:47:00.794Z",taskName:"abc"},{sessionID:"1",timestamp:"2022-06-26T05:47:21.626Z",taskName:"def"},{sessionID:"1",timestamp:"2022-06-26T05:47:21.626Z",taskName:"ghi"},{sessionID:"1",timestamp:"2022-06-26T05:47:21.626Z",taskName:"jkl"},{sessionID:"2",timestamp:"2022-06-26T11:01:48.499Z",taskName:"123"},{sessionID:"2",timestamp:"2022-06-26T11:28:07.389Z",taskName:"456"}];

var result = Object.values(a.reduce(function(agg, item) {
  agg[item.sessionID] = agg[item.sessionID] || [];
  agg[item.sessionID].push(item.taskName)
  return agg
}, {})).map(function(item) {
  return item.join("<<<");
})
console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading