Link to home
Start Free TrialLog in
Avatar of bamford_sup
bamford_sup

asked on

Convert values in an array to percentage

Hello experts,

I want to take an array containing numbers, find the highest number within and change it to 100 (which represents 100%).

I then want to change all the remaining numbers to a percentage of the original highest number.

So for example if I had the following array:

var store = new Array(18, 200, 124, 98)

...I want it to end up like this...

(9, 100, 64, 49)

200 becomes 100 as it is the largest number in the array, 18 becomes 9 as it's 9% of 200, 124 becomes 64 as it's 64% of 200, etc...

Thanks in advance!
Avatar of BenMorel
BenMorel

Hi, here it is :)
Ben
function percent(array)
{
 var i, max=0;
 var newarray = new Array();
 
 for (i=0; i<array.length; i++)
  if (array[i] > max) max = array[i]; 
 
 for (i=0; i<array.length; i++)
  newarray[i] = array[i] * 100 / max;
 
 return newarray;
}
 
/* Example */
 
var store = new Array(18, 200, 124, 98);
 
store = percent(store);
 
for (var i=0; i<store.length; i++)
{
 document.write(store[i] + "\n");
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of BenMorel
BenMorel

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bamford_sup

ASKER

Great, thanks for the quick response! Works perfectly.