Home > Enterprise >  Find the most common elements in array of objects
Find the most common elements in array of objects

Time:03-21

[{
    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?

CodePudding user response:

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])

  • Related