Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the most common elements in array of objects

[{
    country: "US",
    languages: [
      "en"
    ]
  },
  {
    country: "BE",
    languages: [
      "nl",
      "fr",
      "de"
    ]
  },
  {
    country: "NL",
    languages: [
      "nl",
      "fy"
    ]
  },
  {
    country: "DE",
    languages: [
      "de"
    ]
  },
  {
    country: "ES",
    languages: [
      "es"
    ]
  }
]

given the above object, listing some countries objects, how can I find the most common official language(s), of all countries using javascript?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use a data structure that is well suited for lookups i. e. a Map or just a simple JavaScript Object (lookup in O(1)) and store all languages and a count of their occurrences there.

After you have done that, sort the occurrences and select the first item (when sorting in descending order) and you will have the item with the most occurrences.

Here an implementation using Map.

const data = [{
    country: "US",
    languages: [
      "en"
    ]
  },
  {
    country: "BE",
    languages: [
      "nl",
      "fr",
      "de"
    ]
  },
  {
    country: "NL",
    languages: [
      "nl",
      "fy"
    ]
  },
  {
    country: "DE",
    languages: [
      "de"
    ]
  },
  {
    country: "ES",
    languages: [
      "es"
    ]
  }
]

const countLanguages = new Map();
data.forEach(country => {
    country.languages.forEach(lang => {
        if(!countLanguages.has(lang)){
            countLanguages.set(lang, 1);
        }
        else countLanguages.set(lang, countLanguages.get(lang) + 1);
    })
    
})


const sorted = [...countLanguages.entries()].sort();
console.log("Most occurrences:", sorted[0])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading