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

如何基于两个数组生成带投票占比属性的新数组

为投票选项计算得票占比并生成新数组

问题描述

我有两个数组:

  • 投票数组:每个对象代表一次投票,vote_id对应被投票项目的ID
  • 选项数组:包含所有投票选项

需要生成一个新数组,保留每个选项的原有属性,同时新增percentage属性记录该选项的得票占比。


示例数据

投票数组

const votes = [
  { vote_id: 1, person: { name: 'alan' } },
  { vote_id: 2, person: { name: 'John' } },
  { vote_id: 1, person: { name: 'khan' } },
  { vote_id: 1, person: { name: 'martin' } },
  { vote_id: 3, person: { name: 'mike' } }
];

选项数组

const options = [
  { id: 1, title: 'sweet' },
  { id: 2, title: 'salty' },
  { id: 3, title: 'spicy' },
  { id: 4, title: 'bitter' }
];

期望结果

const result = [
  { id: 1, title: 'sweet', percentage: '60%' },
  { id: 2, title: 'salty', percentage: '20%' },
  { id: 3, title: 'spicy', percentage: '20%' },
  { id: 4, title: 'bitter', percentage: '0%' }
];

实现步骤

  1. 计算总有效票数:直接取投票数组的长度(若存在无效投票可先过滤)
  2. 统计每个选项的得票数:用对象累加每个vote_id的出现次数
  3. 遍历选项数组生成结果:根据统计的票数计算占比,无得票则占比为0%

代码实现

// 计算总票数
const totalVotes = votes.length;

// 统计每个vote_id的得票数
const voteCount = votes.reduce((acc, vote) => {
  const id = vote.vote_id;
  acc[id] = (acc[id] || 0) + 1;
  return acc;
}, {});

// 生成带占比的结果数组
const result = options.map(option => {
  const count = voteCount[option.id] || 0;
  // 处理总票数为0的情况,避免除以0错误
  const percentage = totalVotes === 0 ? '0%' : `${Math.round((count / totalVotes) * 100)}%`;
  return {
    ...option,
    percentage
  };
});

console.log(result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 11:57:17