例如[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]
答案 0 :(得分:4)
你能看到这个解决方案吗?
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 )
答案 1 :(得分:3)
您可以检查数组是否包含全零,然后获取部件的长度或获取部件的总和。
function getParts(array) {
var sum = array.reduce((s, v) => s + v, 0);
return sum
? array.map(v => 100 * v / sum)
: array.map((_, __, a) => 100 / a.length);
}
console.log([[0, 0], [1, 1], [1, 2, 3], [0, 0, 1]].map(getParts))

.as-console-wrapper { max-height: 100% !important; top: 0; }