AsgerL
AsgerL

Reputation: 11

Finding percentage values given min and max in JavaScript

I am very new to JavaScript and programming, so i hope you'll bear with me. I am trying to write a program that places a pointer on a scale. The min and max values of the scale, as well as the values in between, changes depending on use. I am trying to define my minimum value as 0%, my max value as 100% and want to be able to place all other values in between.

sortedResults = testResults.sort((a, b) => a - b);

SortedMin = sortedResults[0];
SortedMax = sortedResults[sortedResults.length - 1];

console.log(SortedMin);
console.log(SortedMax);

the values are taken from the sortedResults array and I am able to find the min and max, but simply cant figure out where to start.

Upvotes: 0

Views: 2699

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You could take a closure over min and max value and subtract min from value and max and get the percent value of both numbers.

const
    getPercent = (min, max) => value => 100 * (value - min) / (max - min),
    testResults = [5, 2, 4, 3, 1],
    minVal = Math.min(...testResults),
    maxVal = Math.max(...testResults),
    sample = getPercent(minVal, maxVal);

console.log(testResults.map(sample));

Upvotes: 3

Related Questions