I have an array filled with positive int values, how could I normalize this list so the max value is always 100? Thank you in advance!
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The idea is to first find the highest number in your array (using
applyonMath.max), then find the ratio between that highest number and 100.After that, it’s just a matter of looping through your array and dividing all your numbers by that ratio:
Here’s the fiddle: http://jsfiddle.net/XpRR8/
Note: I’m using
Math.roundto round the numbers to the nearest integer. If you instead prefer to keep them as floats, just remove the function call:Here’s the fiddle: http://jsfiddle.net/XpRR8/1/
If you don’t have to support IE8 and below, you can use
Array.prototype.map():Here’s the fiddle: http://jsfiddle.net/XpRR8/2/
If you do support IE8, but are anyhow using jQuery, you can use
$.map()instead:Here’s the fiddle: http://jsfiddle.net/XpRR8/3/
Update: As pointed out by @wvxvw in the comments below, if you’re concerned about fringe implementations that impose an artificial limit on the amount of arguments
applywill handle, then use a loop instead ofMath.max.apply. Here’s an example (assuming neitherArray.prototype.mapnor$.mapare available):Here’s the fiddle: http://jsfiddle.net/XpRR8/4/
If you’re using ES6, this becomes laughably simple: