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

Javascript array of objects: If objects have duplicate region value, return the object that has a status of "issued"

I have an array of objects with regions and status keys. If there are duplicate regions and one of those duplicate regions has a status of "issued" I want to return that object with the status of "issued" and remove the other duplicates.

const arr = [
  {region: 'US', status: 'pending'},
  {region: 'US', status: 'restart'},
  {region: 'US', status: 'issued'},
  {region: 'FR', status: 'pending'},
  {region: 'FR', status: 'issued'},
  {region: 'MX', status: 'pending'},
  {region: 'MX', status: 'restart'},
  {region: 'KY', status: 'loading'},

];

My goal is to return the following…

const arr = [
  {region: 'US', status: 'issued'},
  {region: 'FR', status: 'issued'},
  {region: 'MX', status: 'pending'},
  {region: 'MX', status: 'restart'},
  {region: 'KY', status: 'loading'},
];

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 :

I’d suggest two passes: one to identify those entries that are issued, and one to make the removals based on that information:

const arr = [{region: 'US', status: 'pending'},{region: 'US', status: 'restart'},{region: 'US', status: 'issued'},{region: 'FR', status: 'pending'},{region: 'FR', status: 'issued'},{region: 'MX', status: 'pending'},{region: 'MX', status: 'restart'},{region: 'KY', status: 'loading'},];

// First pass
const issued = new Set(arr.map(o => o.status === 'issued' && o.region));
// Second pass
const result = arr.filter(o => !issued.has(o.region) || o.status === 'issued');

console.log(result);

NB: the set issued will also collect a false value, but that will never match with a string, so I just didn’t bother to remove it.

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