I've been attempting to extract the top n
languages from an array of country objects and present them as an object containing the language and its count value. My approach involved using nested loops, but I encountered a roadblock in the process.
Below is a snippet showcasing the array of country Objects...
const countries = [
{
name: 'Afghanistan',
capital: 'Kabul',
languages: ['Pashto', 'Uzbek', 'Turkmen'],
population: 27657145,
flag: 'https://restcountries.eu/data/afg.svg',
currency: 'Afghan afghani'
},
{
name: 'Åland Islands',
capital: 'Mariehamn',
languages: ['Swedish'],
population: 28875,
flag: 'https://restcountries.eu/data/ala.svg',
currency: 'Euro'
},
{
name: 'Albania',
capital: 'Tirana',
languages: ['Albanian'],
population: 2886026,
flag: 'https://restcountries.eu/data/alb.svg',
currency: 'Albanian lek'
},
{
name: 'Algeria',
capital: 'Algiers',
languages: ['Arabic'],
population: 40400000,
flag: 'https://restcountries.eu/data/dza.svg',
currency: 'Algerian dinar'
},
{
name: 'American Samoa',
capital: 'Pago Pago',
languages: ['English', 'Samoan'],
population: 57100,
flag: 'https://restcountries.eu/data/asm.svg',
currency: 'United State Dollar'
},
{
name: 'Andorra',
capital: 'Andorra la Vella',
languages: ['Catalan'],
population: 78014,
flag: 'https://restcountries.eu/data/and.svg',
currency: 'Euro'
},
{
name: 'Angola',
capital: 'Luanda',
languages: ['Portuguese'],
population: 25868000,
flag: 'https://restcountries.eu/data/ago.svg',
currency: 'Angolan kwanza'
},
{
name: 'Anguilla',
capital: 'The Valley',
languages: ['English'],
population: 13452,
flag: 'https://restcountries.eu/data/aia.svg',
currency: 'East Caribbean dollar'
}]
The expected output should resemble this
// Desired output format
console.log(mostSpokenLanguages(countries, 5))
/*[
{country: 'English',count:91},
{country: 'French',count:45},
{country: 'Arabic',count:25},
{country: 'Spanish',count:24},
{country:'Russian',count:9}
]*/
This is my attempted solution
const mostSpokenLanguage = (arr, count) => {
let languageCountObjArr = [];
let languagesArr = arr.map(countryObj => countryObj.languages);
console.log('Languages Array', languagesArr);
languagesArr.forEach(languageArr => {
for (let i = 0; i < languageArr.length; i++) {
/* Hit a snag here
let langObj = {
country: languageArr[i],
count: 1
};
if (languageCountObjArr[i].country === languageArr[i]) {
let
}*/
languageCountObjArr.push(langObj);
}
});
languageCountObjArr = languageCountObjArr.slice(count);
return languageCountObjArr;
};
As someone relatively new to JavaScript, I'm still navigating through these challenges. Any assistance on this query would be greatly appreciated.