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

如何在JavaScript中用reduce分组后统计IN/OUT方向的次数

分组统计IN/OUT出现次数的解决方案

修正后的完整代码

import React from 'react'

type Props = {}
// Data
const data = [
  {
    Person: 'Jake',
    Item_tag: '123',
    date: 'Mon May 11 2020',
    direction: 'IN',
  },
  {
    Person: 'Mary',
    Item_tag: '123',
    date: 'Mon May 11 2020',
    direction: 'OUT',
  },
  {
    Person: 'Jake',
    Item_tag: '123',
    date: 'Tue May 12 2020',
    direction: 'IN',
  },
  {
    Person: 'Jake',
    Item_tag: '123',
    date: 'Tue May 12 2020',
    direction: 'OUT',
  },
]

const result = data.reduce((res, current) => {
  const key = `${current.Person}_${current.Item_tag}`
  // 初始化分组对象,计数用数字类型
  res[key] = res[key] || {
    Person: current.Person,
    Item_tag: current.Item_tag,
    Count_of_incoming: 0,
    Count_of_outgoing: 0,
  }
  // 根据direction更新对应计数
  if (current.direction === 'IN') {
    res[key].Count_of_incoming += 1
  } else if (current.direction === 'OUT') {
    res[key].Count_of_outgoing += 1
  }
  return res
}, {})

// 转换为期望的输出格式
const formattedOutput = Object.values(result).map(item => 
  `Person: ${item.Person} Item_tag:${item.Item_tag} Incoming: ${item.Count_of_incoming} outgoing:${item.Count_of_outgoing}`
).join('\n\n')

console.log(formattedOutput)

关键修正点说明

  • 计数类型修正:把初始化时的字符串'0'改成数字0,避免累加时出现字符串拼接错误(比如'0'+1会变成'01'而非预期的1)。
  • 修复语法错误:补全了分组对象初始化时缺失的闭合括号,确保代码能正常运行。
  • 增加计数逻辑:在遍历每个数据项时,根据current.direction的值,对应递增Count_of_incoming或Count_of_outgoing的数值。
  • 格式化输出:将最终的分组结果转换为你需要的文本格式,用换行分隔每个分组信息。

测试示例数据输出

如果使用你提供的第一个示例数据:

const data = [
  {
    Person: 'Jake',
    Item_tag: '124',
    date: 'Mon May 11 2020',
    direction: 'IN',
  },
  {
    Person: 'Jake',
    Item_tag: '123',
    date: 'Tue May 12 2020',
    direction: 'IN',
  },
  {
    Person: 'Jake',
    Item_tag: '123',
    date: 'Tue May 12 2020',
    direction: 'OUT',
  },
]

运行代码后会输出:

Person: Jake Item_tag:124 Incoming: 1 outgoing:0

Person: Jake Item_tag:123 Incoming: 1 outgoing:1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:19:47