在对象数组中找到最常见的元素

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"
    ]
  }
]

鉴于上面的对象,列出了一些国家对象,我如何找到所有使用 javascript 的国家中最常用的官方语言?

使用非常适合查找的数据结构 i。 e.一个 Map 或只是一个简单的 JavaScript 对象(在 O(1) 中查找)并存储所有语言及其出现次数。

完成后,对出现次数和 select 第一个项目进行排序(当按降序排序时),您将得到出现次数最多的项目。

这里是使用 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])