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!
bamford_supAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

BenMorelCommented:
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

0
BenMorelCommented:
Sorry here is a shorter version :)
function percent(array)
{
 var i, max=0;
 
 for (i=0; i<array.length; i++)
  if (array[i] > max) max = array[i]; 
 
 for (i=0; i<array.length; i++)
  array[i] = array[i] * 100 / max;
 
 return array;
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
bamford_supAuthor Commented:
Great, thanks for the quick response! Works perfectly.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.