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

JavaScript实现按yearhalf分组并累加同城市distance到嵌套数组

按yearhalf分组并追加同城市的distance值

基础数组

const arr1 = [
{id:'1',city:'Sydney',distance:100,yearhalf:'2022_1'},
{id:'2',city:'Melbourne',distance:70,yearhalf:'2022_1'},
{id:'3',city:'Perth',distance:65,yearhalf:'2022_1'},
{id:'4',city:'Sydney',distance:89,yearhalf:'2022_2'},
{id:'5',city:'Melbourne',distance:40,yearhalf:'2022_2'},
{id:'6',city:'Perth',distance:40,yearhalf:'2022_2'}
]

当前分组实现代码

const groupedArray = arr1.reduce((acc,item)=>{
        const itemIndex = acc.findIndex(i=>i.yearhalf === item.yearhalf);

        if(itemIndex !== -1){
            acc[itemIndex][item.city]=[item.distance]
        }
        else{
          acc.push({
             [item.city]:[item.distance],
             yearhalf:item.yearhalf
          })
        }
        return acc;
      },[])

当前实现效果

[
{yearhalf:'2022_1',Sydney:[100],Melbourne:[70],Perth:[65]},
{yearhalf:'2022_2',Sydney:[89],Melbourne:[40],Perth:[40]},
]

需求说明

当存在同一city和同一yearhalf的组合(id不同)时,需要将对应的distance值追加到已有的结果数组中,而非覆盖。

例如,给arr1新增以下条目:

{id:'7',city:'Sydney',distance:50,yearhalf:'2022_1'},
{id:'8',city:'Melbourne',distance:40,yearhalf:'2022_1'}

期望结果

[
{yearhalf:'2022_1',Sydney:[100,50],Melbourne:[70,40],Perth:[65]},
{yearhalf:'2022_2',Sydney:[89],Melbourne:[40],Perth:[40]},
]

注意事项

  • 城市名称仅为Sydney/Melbourne/Perth中的一种
  • yearhalf可以有更多实例(如YYYY_1、YYYY_2)

解决方案

修改reduce逻辑,判断分组中是否已存在对应城市的数组,存在则追加distance,不存在则初始化数组:

const groupedArray = arr1.reduce((acc, item) => {
  // 直接获取对应yearhalf的分组对象
  const targetGroup = acc.find(group => group.yearhalf === item.yearhalf);

  if (targetGroup) {
    // 分组存在时,判断城市数组是否已初始化
    if (targetGroup[item.city]) {
      // 已存在则追加distance
      targetGroup[item.city].push(item.distance);
    } else {
      // 未存在则初始化数组
      targetGroup[item.city] = [item.distance];
    }
  } else {
    // 分组不存在时,创建新分组
    acc.push({
      yearhalf: item.yearhalf,
      [item.city]: [item.distance]
    });
  }

  return acc;
}, []);

逻辑优化说明

  1. 用find替代findIndex,直接获取分组对象,代码更简洁
  2. 取消直接覆盖城市数组的逻辑,改为判断后追加,满足同城市同yearhalf的累加需求
  3. 明确区分分组不存在、分组存在但城市未初始化、分组存在且城市已初始化三种场景,逻辑更严谨

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 01:31:08