Javascript:从给定值计算数组比率

时间:2020-12-07 21:18:00

I am trying to calculate the resulting ratio value for a given number distributed proportionally on a given array. The array length will be random. eg

我试图计算在给定数组上按比例分配的给定数字的结果比值。数组长度是随机的。例如

var arr = [45,23,7]
function array(arr){
    var share = 3250.00
    // logic to share the array 
    return array
}

I can't seem to get the distribution right, I know there is neither Math.sum nor Math.ration, what's the best approach to this without running into complex normalizations

我似乎无法正确分配,我知道既没有Math.sum也没有Math.ration,如果没有遇到复杂的规范化,最好的方法是什么

1 个解决方案

#1


3  

This should do the trick, assuming you're trying to distribute the share value proportionally amongst the members of arr based on their proportion of the total sum of the array:

这应该可以解决这个问题,假设您尝试根据数组总和的比例在arr成员中按比例分配共享值:

var arr = [45,23,7];

function ration(arr, share){
    var total = arr.reduce(function(x, y) {
      return x + y;
    });
    return arr.map(function(x) {
      return (x / total) * share;
    });
}

var rationedArr = ration(arr, 3250.00);

I've broken the share value out into an argument to make the function more flexible, and renamed the function ration because calling it array is a bad idea.

我已经将共享值分解为一个参数以使函数更灵活,并重命名函数比例,因为调用它是一个坏主意。

#1


3  

This should do the trick, assuming you're trying to distribute the share value proportionally amongst the members of arr based on their proportion of the total sum of the array:

这应该可以解决这个问题,假设您尝试根据数组总和的比例在arr成员中按比例分配共享值:

var arr = [45,23,7];

function ration(arr, share){
    var total = arr.reduce(function(x, y) {
      return x + y;
    });
    return arr.map(function(x) {
      return (x / total) * share;
    });
}

var rationedArr = ration(arr, 3250.00);

I've broken the share value out into an argument to make the function more flexible, and renamed the function ration because calling it array is a bad idea.

我已经将共享值分解为一个参数以使函数更灵活,并重命名函数比例,因为调用它是一个坏主意。