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

使用JavaScript reduce方法按title分组对象数组实现关联商品匹配

问题说明

实现商品数组分组逻辑时,因不熟悉reduce方法用法,长时间调试未达到预期效果:需要基于商品的title字段给商品对象数组的每一项新增linked_products属性,属性值为与当前商品title相同的其他商品组成的数组,无同title商品时属性值为空数组。

初始代码框架如下:

const products = [
    {
        id: 1,
        title: 't-shirt'
    },
    {
        id: 2,
        title: 't-shirt'
    },
    {
        id: 3,
        title: 'jeans'
    }
]

const linked_products = products.reduce((prevProduct, product) => {
    
}, [])

products.forEach(product => {
  // this is an array of objects
  // it's an array of objects with the same title
  product.linked_products = linked_products
})

预期输出效果:

products = [
  {
    id: 1,
    title: 't-shirt',
    // here is the new property
    linked_products: [
      { id: 2, title: 't-shirt'}
    ]
  },
  {
    id: 2,
    title: 't-shirt',
    linked_products: [
      { id: 1, title: 't-shirt'}
    ]
  },
  {
    id: 3,
    title: 'jeans',
    linked_products: []
  }
]
实现代码

原代码里给reduce设置数组作为初始累加值不利于快速分组,改用对象作为分组容器效率更高,补全后的完整可运行代码如下:

const products = [
    {
        id: 1,
        title: 't-shirt'
    },
    {
        id: 2,
        title: 't-shirt'
    },
    {
        id: 3,
        title: 'jeans'
    }
]

// reduce阶段按title完成商品分组
const groupedMap = products.reduce((acc, product) => {
    if (!acc[product.title]) {
        acc[product.title] = []
    }
    acc[product.title].push(product)
    return acc
}, {})

// 遍历给每个商品挂载关联商品
products.forEach(product => {
  // 过滤掉当前商品自身,得到同title的其他商品
  product.linked_products = groupedMap[product.title].filter(item => item.id !== product.id)
})
逻辑说明
  • reduce遍历过程中,累加器acc是一个对象,以商品title为键,值为对应该title下的所有商品数组,遍历完成后会得到{ 't-shirt': [id1商品, id2商品], 'jeans': [id3商品] }结构的分组结果
  • 后续遍历原数组时,直接取当前商品title对应的分组数组,过滤掉id和当前商品一致的项(即商品自身),赋值给linked_products即可,单个商品的分组过滤后自然得到空数组,完全符合预期要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 15:51:19