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

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!
0
bamford_sup
Asked:
bamford_sup
  • 2
1 Solution
 
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
 
bamford_supAuthor Commented:
Great, thanks for the quick response! Works perfectly.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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