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

如何对比两个对象数组后为对象添加isSupported属性

优化国家列表标记支持状态的实现方案

我们需要给全量国家列表allCountries中的每个对象添加isSupported字段,判断依据是该国家是否存在于支持列表supportedCountries中——存在则为true,否则为false。以下是相关代码、期望输出,以及针对现有实现的优化方案。

原始数据与期望输出

全量国家数组

const allCountries = [
  {
    name: 'Albania',
    code: 'AL',
    'alpha-3': 'ALB',
    numeric: '8',
  },
  {
    name: 'Algeria',
    code: 'DZ',
    'alpha-3': 'DZA',
    numeric: '12',
  },
  {
    name: 'Andorra',
    code: 'AD',
    'alpha-3': 'AND',
    numeric: '20',
  },
  {
    name: 'Angola',
    code: 'AO',
    'alpha-3': 'AGO',
    numeric: '24',
  },
  {
    name: 'Antigua and Barbuda',
    code: 'AG',
    'alpha-3': 'ATG',
    numeric: '28',
  },
  {
    name: 'Argentina',
    code: 'AR',
    'alpha-3': 'ARG',
    numeric: '32',
  },
];

支持的国家数组

const supportedCountries = [
  {
    name: 'Algeria',
    code: 'DZ',
    'alpha-3': 'DZA',
    numeric: '12',
  },
  {
    name: 'Angola',
    code: 'AO',
    'alpha-3': 'AGO',
    numeric: '24',
  },
  {
    name: 'Argentina',
    code: 'AR',
    'alpha-3': 'ARG',
    numeric: '32',
  },
];

期望输出

[
  {
    name: "Albania",
    code: "AL",
    "alpha-3": "ALB",
    numeric: "8",
    isSupported: false
  },
  {
    name: "Algeria",
    code: "DZ",
    "alpha-3": "DZA",
    numeric: "12",
    isSupported: true
  },
  ... 
];

现有实现的问题

当前的实现逻辑存在明显的性能冗余:

  • 嵌套forEach循环导致时间复杂度达到O(n*m),数组规模越大性能越差
  • 先重复添加元素再通过reduce+find去重,额外增加了**O(n²)**的计算开销,且逻辑冗余容易出错
const newSet = [];

allCountries.forEach((country) => {
  supportedCountries.forEach((b4b) => {
    if (country.code === b4b.code) {
      newSet.push({ ...country, isSupported: true });
    }
  });
  newSet.push({ ...country, isSupported: false });
});

const uniqueCountries = newSet.reduce((accumulator, current) => {
  if (!accumulator.find((item) => item.code === current.code)) {
    accumulator.push(current);
  }
  return accumulator;
}, []);

优化方案

方案一:用Set实现高效查找(推荐)

通过把支持国家的code提取到Set中,将查找操作的时间复杂度降到O(1),整体时间复杂度优化为O(n+m):

// 提取所有支持国家的code到Set
const supportedCodes = new Set(supportedCountries.map(c => c.code));

// 遍历全量数组,添加isSupported字段
const result = allCountries.map(country => ({
  ...country,
  isSupported: supportedCodes.has(country.code)
}));

方案二:用Map存储支持国家(多字段匹配场景)

如果需要基于多个字段判断匹配,可以将支持国家转成以唯一标识(比如code)为键的Map:

// 构建支持国家的映射表
const supportedMap = supportedCountries.reduce((map, country) => {
  map[country.code] = country;
  return map;
}, {});

// 遍历全量数组标记状态
const result = allCountries.map(country => ({
  ...country,
  isSupported: !!supportedMap[country.code]
}));

优化点说明

  1. 性能提升:时间复杂度从O(n*m + n²)降至O(n+m),大数据量下性能差异显著
  2. 逻辑简洁:直接通过一次遍历完成需求,无冗余中间数组和去重步骤
  3. 可靠性高:避免了原实现中重复添加元素导致的潜在问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:57:56