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

JavaScript中如何过滤数组获取每个用户的最高百分比值

按用户ID提取最高percent值实现方案

实现思路

  • 遍历数组时以userId为唯一标识建立临时映射
  • 对同一用户的多条记录,仅保留percent数值最大的条目
  • 遍历结束后将映射转换为结果数组

代码实现

方案1:保留完整原对象结构

let data = [ 
  {
    "userId": "1",
    "percent": 97.58,
  },
  {
    "userId": "1",
    "percent": 92.01,
  },
  {
    "userId": "2",
    "percent": 91.64,
  },
  {
    "userId": "2",
    "percent": 91.64,
  },
  {
    "userId": "3",
    "percent": 91.64,
  }
];

const maxPerUser = [];
const userMaxMap = new Map();

data.forEach(item => {
  const currentMax = userMaxMap.get(item.userId);
  if (!currentMax || item.percent > currentMax.percent) {
    userMaxMap.set(item.userId, item);
  }
});

maxPerUser.push(...userMaxMap.values());
console.log(maxPerUser);

输出结果

[
  { userId: '1', percent: 97.58 },
  { userId: '2', percent: 91.64 },
  { userId: '3', percent: 91.64 }
]

方案2:仅获取用户ID和对应最高percent值

const userPercentMap = data.reduce((acc, curr) => {
  acc[curr.userId] = Math.max(acc[curr.userId] || -Infinity, curr.percent);
  return acc;
}, {});

console.log(userPercentMap);

输出结果

{ '1': 97.58, '2': 91.64, '3': 91.64 }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 22:39:00