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

如何计算数组中每个元素相对于其他所有元素的百分比数值

实现思路
  • 核心逻辑采用两层遍历:外层遍历每一个数组元素作为基准元素,内层遍历所有数组元素作为对比元素
  • 百分比计算公式:(基准元素 / 对比元素) * 100,结果保留2位小数即可匹配示例显示效果
  • 可按需将结果整理为对象、二维数组等结构方便后续业务调用
代码实现(JavaScript版本)
const arr = [1,2,3,6,7];
// 百分比格式化工具函数,可自定义保留小数位数
const formatPercent = (num, decimal = 2) => num.toFixed(decimal) + '%';

const percentResult = arr.map((base, baseIdx) => {
  const compareList = arr.map((compare, compareIdx) => {
    const percentVal = (base / compare) * 100;
    return {
      compareIndex: compareIdx,
      compareValue: compare,
      percent: formatPercent(percentVal)
    }
  });
  return {
    baseIndex: baseIdx,
    baseValue: base,
    comparePercent: compareList
  }
});

// 按示例格式打印输出
percentResult.forEach(item => {
  const printStr = item.comparePercent.map(p => `是 arr[${p.compareIndex}] 的 ${p.percent}`).join(',');
  console.log(`${item.baseValue} ${printStr};`);
})
运行输出结果

1 是 arr[0] 的 100.00%,是 arr[1] 的 50.00%,是 arr[2] 的 33.33%,是 arr[3] 的 16.67%,是 arr[4] 的 14.29%;
2 是 arr[0] 的 200.00%,是 arr[1] 的 100.00%,是 arr[2] 的 66.67%,是 arr[3] 的 33.33%,是 arr[4] 的 28.57%;
3 是 arr[0] 的 300.00%,是 arr[1] 的 150.00%,是 arr[2] 的 100.00%,是 arr[3] 的 50.00%,是 arr[4] 的 42.86%;
6 是 arr[0] 的 600.00%,是 arr[1] 的 300.00%,是 arr[2] 的 200.00%,是 arr[3] 的 100.00%,是 arr[4] 的 85.71%;
7 是 arr[0] 的 700.00%,是 arr[1] 的 350.00%,是 arr[2] 的 233.33%,是 arr[3] 的 116.67%,是 arr[4] 的 100.00%;

注意事项
  • 如果数组存在值为0的元素,需要额外加判断逻辑避免除以0报错
  • 保留小数位数可通过修改formatPercent函数的第二个参数自定义调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:24:03