javascript - 如何对一组数字求和,使数组的总和为 100

标签 javascript

例如 [1,1] --> [50,50][1,2] --> [33.33, 66.67]

这是我的代码:

let total = getTotal(arrayOfNum);
let remainder =  100 - total;
arrayOfNum.map(n => {
  let newValue = n + ( (remainder / total ) * n);
 return newValue || 0;
});

当数组中的所有项目均为 0 时,此代码无法正确汇总

[0,0,0] --> [0,0,0] 虽然我期待类似 [0,0,0] --> [33.33, 33.33, 33.33]

最佳答案

你能看到这个解决方案吗?

const t = [0,2];

const total = arrayOfNum.reduce((r,n)=>r+n);

arrayOfNum
          .map(n=> n/total)
          .map(n=> !isNaN(n) ? n * 100 : 1/arrayOfNum.length * 100 )

关于javascript - 如何对一组数字求和,使数组的总和为 100,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49730110/

相关文章:

javascript - Ember.js:关于 Controller 、 'this'、 'content' 和模型结构的问题

javascript - 使用 window xp 主题(非经典)时垂直滚动条不起作用

javascript - 哪个 javascript MVC 框架更适合 Symfony 2?

javascript - addEventListener 给 IE8 带来问题。是否可以将我的 JavaScript 转换为 jQuery?

javascript - 如何在多个设备上并行运行测试?

javascript - 在 javascript 或服务器端处理 session 超时

Javascript:检查用户是否通过表单提交或简单的链接单击导航离开

javascript - 从 VuetifyJS/VueJS 中的一个代码库为多个平台构建的代码库结构

javascript - 将值插入对象

javascript - 在 div 上使用 jQuery scrolltop 和 fadein/fadeout