• Status: Solved
• Priority: Medium
• Security: Public
• Views: 2260

# 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...

0
bamford_sup
• 2
1 Solution

Commented:
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");
}
``````
0

Commented:
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;
}
``````
0

Author Commented:
Great, thanks for the quick response! Works perfectly.
0

## Featured Post

• 2
Tackle projects and never again get stuck behind a technical roadblock.