You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于countries与networks数组生成指定结构newState的更优实现方案

优化后实现方案

你可以通过先分组映射再遍历生成的方式简化代码,同时降低时间复杂度,运行结果和你现有代码完全一致:

const networks = [
    {
        id: 1,
        name: "royal warmth",
        country: "Netherlands"
    },
    {
        id: 2,
        name: "interested power",
        country: "United Kingdom"
    },
    {
        id: 3,
        name: "drunk prejudice NL",
        country: "Netherlands"
    },
    {
        id: 10,
        name: "small Media promotion FR",
        country: "France"
    },
    {
        id: 11,
        name: "experimental vat FR",
        country: "France"
    },
]

const countries = [
    {
        id: 122,
        name: "Afghanistan"
    },
    {
        id: 190,
        name: "France"
    },
    {
        id: 210,
        name: "Netherlands"
    },
    {
        id: 226,
        name: "United Kingdom"
    }
]

// 预处理networks,按国家名称分组,直接生成符合要求的network结构
const countryNetworkMap = networks.reduce((map, item) => {
  const { country, ...networkInfo } = item
  if (!map[country]) map[country] = []
  map[country].push(networkInfo)
  return map
}, {})

// 遍历国家数组生成最终结果,过滤掉没有对应网络的国家
const newState = countries
  .filter(country => countryNetworkMap[country.name]?.length)
  .map(country => ({
    id: country.id,
    name: country.name,
    networks: countryNetworkMap[country.name]
  }))

console.log(newState)

优化点说明

  • 时间复杂度更低:原来的嵌套循环时间复杂度为O(m*n)(m为国家数组长度、n为网络数组长度),优化后仅需两次遍历,总时间复杂度为O(m+n),数据量越大性能优势越明显
  • 代码逻辑更清晰:用reduce/filter/map等原生高阶函数替代手动push和嵌套判断,更符合JavaScript的函数式编程习惯,可读性和可维护性更高
  • 拓展性更强:如果后续需要调整网络项的结构或者过滤规则,仅需修改reduce内的逻辑即可,不需要改动最终生成newState的部分

内容的提问来源于stack exchange,提问作者Yana Trifonova

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:48:03