I need a better implementation than the below code (O(N) Solution), I am grouping countries by language ( data ) is the countries JSON, each country could have 0, 1 .. or more language as the object key, value where the key is the language shortcut and the value is the language official name.
module.exports.groupByLanguage = async (data, grouped) => {
try {
data.forEach((country) => {
if (country.languages) {
let countryLanguages = Object.keys(country.languages)
countryLanguages.forEach((language) => {
const keys = Object.keys(grouped.languages)
if (language.toString() in grouped.languages) {
grouped.languages[language].push(country)
} else {
grouped.languages[language] = []
grouped.languages[language].push(country)
}
})
} else {
grouped.languages['notEntries'].push(country)
}
})
} catch (err) {
console.log(err)
}
return grouped
}
JSON for each country
{
"name": {},
"codes": {
"cca2": "MT",
"cca3": "MLT",
"ccn3": "470"
},
"languages": {
"eng": "English",
"mlt": "Maltese"
},
"currencies": {
"EUR": {
"name": "Euro",
"symbol": "€"
}
},
"region": "Europe",
"latlng": [35.83333333, 14.58333333]
}
check out the results Here