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'},
];
CodePudding user response:
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.