Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Need help creating JavaScript function that accepts any array of numbers

1. ## Need help creating JavaScript function that accepts any array of numbers

Hi, I'm new to JS programming and I would appreciate any help or advise with helping me solve an issue that I have. I need to create a function that accepts any array of numbers and returns an array of percentage values for each number on a scale of 0 to the highest number in the array. Round any decimals to two decimal places.

I eventuality would like to call this function from its own JavaScript file and display the return array.

Array I used to test - [2, 12, 4, 7]

Output I have thus far:

12

0.16666666666666666
1
0.3333333333333333
0.5833333333333334

My logic to solve this would look something like this:
1. find the largest number in the array
2. take each number in the array and divide by the largest number in the array
3. round each number to 2 decimal places
4. output to the screen in the format of an array [16.66, 1, 33.33, 58.33]

This is what I have so far:

Code:
```<!DOCTYPE html>
<html>

<body>

<p id="number"></p>

<!-- scripts.js -->
<script>
var myArray = [2, 12, 4, 7];
var largestNumber = Math.max.apply(Math, myArray);
document.getElementById("number").innerHTML = largestNumber; // display largest number in array

for (var i=0; i < myArray.length; i++)
{
myArray[i] /= largestNumber;
document.write(myArray[i] + "<br />");
}
</script>
<!-- scripts.js -->

</body>
</html>```

• document.write(myArray[i].toFixed(2) + "<br />");

Except, of course, document.write is long obsolete and should be avoided at all costs.

You are doing the right thing here: `document.getElementById("number").innerHTML`
Why would you then blow it when displaying the array?

• Originally Posted by Old Pedant
Why would you then blow it when displaying the array?
Thanks for all of your help!
What would you suggest I do to display the array? I'm still trying to learn...

• innerHTML would work fine.

Code:
```	var myArray = [2, 12, 4, 7];
var largestNumber = Math.max.apply(Math, myArray);
document.getElementById("number").innerHTML = largestNumber; // display largest number in array

var result = "";
for (var i=0; i < myArray.length; i++)
{
myArray[i] /= largestNumber;
result += ( myArray[i].toFixed(2) + "<br />");
}
document.getElementById("result").innerHTML = result;```
And just have <p> or <div> with an id of "result".

• ## Users who have thanked Old Pedant for this post:

_Megatron (08-09-2014)

• Code:
```var r=[2, 12, 4, 7];
document.body.innerHTML=JSON.stringify(
r.map(
function(a){return (a/this).toFixed(2) },
Math.max.apply(0, r)
),
null, "\t" );```

•