0

I have an array of objects sample below:

const countriesSample = [{
    name: "Yemen",
    capital: "Sana'a",
    languages: ["Arabic"],
  {
    name: "Zambia",
    capital: "Lusaka",
    languages: ["English"],
  },
  {
    name: "Zimbabwe",
    capital: "Harare",
    languages: ["Shona", "English", "Northern Ndebele"],
  },
];

I'd like to iterate through languages property and return the number of occurrence of each language value like below:

[
  { language: "English", count: 2 },
  { language: "Arabic", count: 1 },
  { language: "Shona", count: 1 },
  { language: "Northern Ndebele", count: 1 }
  
];
I have tried looping through the object but the it doesn't return any value:

let totalOccurence = 0;
for (let i = 0; i < countries.length; i++) {
  for (let j = 0; j < countries[i].length; j++) {
    totalOccurence += countries[j].length;
    console.log(`language: ${countries[j].languages}, count:${totalOccurence} `);
  }
}

Is there any other method that I can achieve the expected result without using loops?

2
  • 2
    Welcome to stack overflow! Questions works a bit better here if you show some effort. What is stopping you from completing this task? What have you tried so far? And how did that attempt not meet your goal? Please review How to ask then edit your question with additional info about your attempts so far. Commented Jun 17, 2022 at 23:31
  • @alex-wayne Thanks for your feedback. I have made the necessary changes. Hopefully, the question has almost if not fully met the requirement. It's my first time asking questions here and it's great to learn from experts like you. Appreciate your feedback. Commented Jun 18, 2022 at 7:43

1 Answer 1

1

Use Array#reduce, looping over the languages for each object and using an object to keep track of the frequency of each language.

const countriesSample=[{name:"Yemen",capital:"Sana'a",languages:["Arabic"]},{name:"Zambia",capital:"Lusaka",languages:["English"]},{name:"Zimbabwe",capital:"Harare",languages:["Shona","English","Northern Ndebele"]}];
let res = Object.values(countriesSample.reduce((acc, {languages})=>{
  languages.forEach(language => ++(acc[language] ??= {language, count: 0}).count);
  return acc;
},{}));
console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.