I have two arrays of objects. One array represents list of all countries:
const allCountries = [
{
name: 'Albania',
code: 'AL',
'alpha-3': 'ALB',
numeric: '8',
},
{
name: 'Algeria',
code: 'DZ',
'alpha-3': 'DZA',
numeric: '12',
},
{
name: 'Andorra',
code: 'AD',
'alpha-3': 'AND',
numeric: '20',
},
{
name: 'Angola',
code: 'AO',
'alpha-3': 'AGO',
numeric: '24',
},
{
name: 'Antigua and Barbuda',
code: 'AG',
'alpha-3': 'ATG',
numeric: '28',
},
{
name: 'Argentina',
code: 'AR',
'alpha-3': 'ARG',
numeric: '32',
},
];
The other array represents list of supported countries:
const supportedCountries = [
{
name: 'Algeria',
code: 'DZ',
'alpha-3': 'DZA',
numeric: '12',
},
{
name: 'Angola',
code: 'AO',
'alpha-3': 'AGO',
numeric: '24',
},
{
name: 'Argentina',
code: 'AR',
'alpha-3': 'ARG',
numeric: '32',
},
];
What I needed is to create another array of countries with isSupported: true or isSupported: false added to allCountries array to be:
[
{
name: "Albania",
code: "AL",
"alpha-3": "ALB",
numeric: "8",
isSupported: false
},
{
name: "Algeria",
code: "DZ",
"alpha-3": "DZA",
numeric: "12",
isSupported: true
},
...
];
My solution is, and it works fine:
const newSet = [];
allCountries.forEach((country) => {
supportedCountries.forEach((b4b) => {
if (country.code === b4b.code) {
newSet.push({ ...country, isSupported: true });
}
});
newSet.push({ ...country, isSupported: false });
});
const uniqueCountries = newSet.reduce((accumulator, current) => {
if (!accumulator.find((item) => item.code === current.code)) {
accumulator.push(current);
}
return accumulator;
}, []);
My question is, what would be the better/cleaner/neater solution for this?