Search code examples
javascriptarraysecmascript-6setjavascript-objects

Store the unique values of two properties from array of objects into single array


How to get unique values of requesterPractitionerId & performerOrganizationId. I need to stroe the unique values of requesterPractitionerId & performerOrganizationId in a single array.

[ 
    { 
        id: '1043120',
        requesterPractitionerId: '1043119',
    },
    { 
        id: '1043081',
        requesterPractitionerId: '1043080'
    },
    { 
        id: 'e1dceebe-c5ba-46a5-a63a-bff709896af4',
        requesterPractitionerId: 'e0a844e4-6c8a-489a-8bd6-1d62267d311e',
        performerOrganizationId: '05D0889009',
    },
    { 
        id: '2709842f-41e3-4193-8607-fc34d3d24ec1',
        requesterPractitionerId: 'e0a844e4-6c8a-489a-8bd6-1d62267d311e',
        performerOrganizationId: '05D0889009'
    } 
]

Expected Output:

1043119
1043080
e0a844e4-6c8a-489a-8bd6-1d62267d311e
05D0889009

I am new to Javascript and struggling with this for a couple of hours. Any help would be realy aapreciated.


Solution

  • Use Set, Array.reduce and Array.from

    • Use reduce to create a set with unique values of the said fields
    • Then convert the set to array using Array.from

    let arr = [{id:'1043120',requesterPractitionerId:'1043119'},{id:'1043081',requesterPractitionerId:'1043080'},{id:'e1dceebe-c5ba-46a5-a63a-bff709896af4',requesterPractitionerId:'e0a844e4-6c8a-489a-8bd6-1d62267d311e',performerOrganizationId:'05D0889009'},{id:'2709842f-41e3-4193-8607-fc34d3d24ec1',requesterPractitionerId:'e0a844e4-6c8a-489a-8bd6-1d62267d311e',performerOrganizationId:'05D0889009'}];
    
    let result = Array.from(arr.reduce((a,c) => {
      if(c.requesterPractitionerId) a.add(c.requesterPractitionerId);
      if(c.performerOrganizationId) a.add(c.performerOrganizationId);
      return a;
    }, new Set()));
    
    console.log(result);