Asabeneh / 30-Days-Of-JavaScript

30 days of JavaScript programming challenge is a step-by-step guide to learn JavaScript programming language in 30 days. This challenge may take more than 100 days, please just follow your own pace. These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
43.24k stars 10.03k forks source link

[Need-Help]: How to return an array of objects from reduce method? #687

Open alamenai opened 1 year ago

alamenai commented 1 year ago

Question : Find the 10 most spoken languages:

const mostSpokenLanguage = (countries, limit) =>
  countries
    .map((country) => country.languages)
    .flat()
    .reduce((acc, language) => {
      return acc[language] ? ++acc[language] : (acc[language] = 1), acc;
    }, []);

console.log(mostSpokenLanguage(countriesList, 10));

Current :

 Uzbek: 2,
  Turkmen: 2,
  Swedish: 3,
  Albanian: 3,
  Arabic: 25,
  English: 91,

Expected:

{country: Uzbek, count:2}
{.....},
{.....}
xfkrahmad commented 1 year ago

make an object, so you can create the key then the values

VijayalakshmiGanesh commented 1 year ago

Question : Find the 10 most spoken languages:

const mostSpokenLanguage = (countries, limit) =>
  countries
    .map((country) => country.languages)
    .flat()
    .reduce((acc, language) => {
      return acc[language] ? ++acc[language] : (acc[language] = 1), acc;
    }, []);

console.log(mostSpokenLanguage(countriesList, 10));

Current :

 Uzbek: 2,
  Turkmen: 2,
  Swedish: 3,
  Albanian: 3,
  Arabic: 25,
  English: 91,

Expected:

{country: Uzbek, count:2}
{.....},
{.....}
const mostSpokenLanguage = (countries, limit) =>
  countries
    .map((country) => country.languages)
    .flat()
    .reduce((acc, language) => {
    let counter = acc[language] ? ++acc[language] : (acc[language] = 1)
      return {country: language, count: counter}, acc;
    }, []);

console.log(mostSpokenLanguage(countriesList, 10));

Above code will work ig