-2

I want to generate a proportional array of numbers between 0 and 1 with an array of sales that has different size values.

For example if I have the values [1, 80, 2000] it would be ok an array like [0.1, 0.4, 1].

JJJ
  • 32,902
  • 20
  • 89
  • 102
Sergio
  • 19
  • 1
  • 6

2 Answers2

3

a modern functional approach:

var r=[1, 80, 2000] ;

r.map(function(a){
   return a/this;
}, Math.max.apply(0,r) );

//==[0.0005,0.04,1]

i think math was off in OP...

edit: details on what's going on here: The problem is broken down into two steps.

  1. find the largest number in the Array
  2. compute each Array item as a portion of the largest item

For the first step, JS provides the Math.max function. To use an argument-based function with an array, the function's apply() method is used, and 0 is passed as "this", but it's not really used; it just needs to be something.

The second step compares each item to the number found in step #1, using the Array.map method to iterate the Array and return the result of an operation upon each item in the Array. Since Array.map() can accept an optional "this" argument, the largest number from step #1 is passed as "this" to avoid a performance-robbing function closure.

dandavis
  • 16,370
  • 5
  • 40
  • 36
0

though it is not clear, what should be the relationship between original array and the generated array. Am assuming you want to create what fraction the item is of the total sum (proportion):

try this:

function generateProportion(arr){

    //find out the total sum..
    var total = 0;
     for(var k=0;k <arr.length;k++)
         total += arr[k];

    //push the ratios into the new array with double precison..
    var newArr = new Array();

    for(var i=0;i< arr.length; i++)
        newArr.push((arr[i]/total).toFixed(2));

    console.log(newArr);
    return newArr;
}

and call it like this:

var a = [1, 80, 2000];
generateProportion(a);

see this fiddle

  • The result is `[0.00, 0.04, 0.96]`. Not quite what's mentioned in the question. – JJJ May 06 '13 at 16:36
  • there's a whole lot of assumptions because of the unclear question of the OP. the answer shows the output with one maths formula. it can be modified to function any. :) –  May 06 '13 at 16:40