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

JavaScript如何高效实现两个数组各元素两两拼接生成目标数组

实现方案

直接用Array.prototype.flatMap搭配Array.prototype.map即可实现,代码逻辑简洁且性能和两层for循环基本一致:

let arr1 = [{a: 1, b: 2}, {a: 3, b: 4}]
let arr2 = [{c: 5}, {c: 6}]

const result = arr1.flatMap(item1 => 
  arr2.map(item2 => `${item1.a}-${item1.b}-${item2.c}`)
)

输出结果为:["1-2-5", "1-2-6", "3-4-5", "3-4-6"](你示例中的3-4,6为笔误,已按逻辑修正为分隔符统一的格式)

兼容旧环境的备选方案

如果需要兼容不支持flatMap的运行环境,可以替换为以下两种写法:

  • 写法1:map + flat组合
const result = arr1.map(item1 => 
  arr2.map(item2 => `${item1.a}-${item1.b}-${item2.c}`)
).flat()
  • 写法2:reduce实现
const result = arr1.reduce((acc, item1) => 
  acc.concat(arr2.map(item2 => `${item1.a}-${item1.b}-${item2.c}`))
, [])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:27:03