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

JavaScript多字段分组计数问题:findIndex返回-1求助

关于JavaScript中findIndex和reduce分组计数的问题

我是JavaScript新手,现有一个关于findIndex函数的问题。我希望按name_station和result_run字段进行分组计数,编写了如下reduce处理代码:

const res = runs.reduce((acc, obj) => {
   const existingIndex = acc.findIndex(
        el => el.name_station === obj.name_station && el.result_run === obj.result_run
        )
   console.log(existingIndex)
   if (existingIndex > -1) {
       acc[existingIndex].count += 1
   } else {
       acc.push({
       station: obj.name_station,
       result: obj.result_run,
       count: 1
       })
   }
   return acc
}, [])
        
console.log(res)

我的数据为:

const runs = [
  { name_station: 'fpc10', result_run: true },
  { name_station: 'fpc10', result_run: false },
  { name_station: 'fpc10', result_run: true },
  { name_station: 't10', result_run: true }
]

但打印existingIndex时始终返回-1(表示条件不匹配),而数据中明明存在匹配项。我的预期输出是:

[
  { name_station: "fpc10", result_run: true, count: 2 }, 
  { name_station: "fpc10", result_run: false, count: 1 }, 
  { name_station: "t10", result_run: true, count:1 }
]

问题原因

核心错误是字段名不匹配:

  • 在findIndex的判断逻辑中,你检查的是对象的name_station和result_run字段;
  • 但在向累加器acc中新增对象时,你用了station和result作为字段名,而非name_station和result_run。

这导致每次查找时,累加器里的对象根本没有判断条件中用到的字段,自然永远匹配失败,findIndex持续返回-1。

修正后的代码

只需将新增对象的字段名和判断逻辑保持一致即可:

const res = runs.reduce((acc, obj) => {
   const existingIndex = acc.findIndex(
        el => el.name_station === obj.name_station && el.result_run === obj.result_run
        )
   if (existingIndex > -1) {
       acc[existingIndex].count += 1
   } else {
       acc.push({
       name_station: obj.name_station, // 修正字段名
       result_run: obj.result_run,     // 修正字段名
       count: 1
       })
   }
   return acc
}, [])
        
console.log(res)

如果需要将result_run转为字符串类型(如预期输出中的"true"),可以在新增对象时做类型转换:result_run: String(obj.result_run)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:06:09