Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Make numbers in array relative to 0 – 100 in JavaScript
Let's say, we have an array that contains some numbers, our job is to write a function that takes in the array and maps all the values relative to 0 to 100. This means that the greatest number should get replaced by 100, the smallest by 0, and all others should get converted to specific numbers between 0 and 100 according to the ratio.
Understanding the Formula
To normalize values to a 0-100 scale, we use the formula:
normalizedValue = ((value - min) / (max - min)) * 100
This formula ensures the smallest value becomes 0 and the largest becomes 100, with all others proportionally scaled.
Example
const numbers = [45.71, 49.53, 18.5, 8.38, 38.43, 28.44];
const mapNumbers = (arr) => {
const max = Math.max(...arr);
const min = Math.min(...arr);
const diff = max - min;
return arr.reduce((acc, val) => acc.concat((100/diff)*(val-min)), []);
};
console.log(mapNumbers(numbers));
Output
[ 90.71688942891859, 100, 24.59295261239368, 0, 73.02551640340218, 48.74848116646417 ]
How It Works
The function calculates the maximum and minimum values from the array, then applies the normalization formula to each element. The reduce() method builds a new array with the transformed values.
Alternative Implementation Using map()
const mapNumbers = (arr) => {
const max = Math.max(...arr);
const min = Math.min(...arr);
const range = max - min;
return arr.map(val => ((val - min) / range) * 100);
};
const numbers = [10, 50, 30, 90, 20];
console.log(mapNumbers(numbers));
[ 0, 50, 25, 100, 12.5 ]
Handling Edge Cases
const mapNumbers = (arr) => {
if (arr.length === 0) return [];
const max = Math.max(...arr);
const min = Math.min(...arr);
const range = max - min;
// If all values are the same, return array of 50s
if (range === 0) return arr.map(() => 50);
return arr.map(val => ((val - min) / range) * 100);
};
// Test with identical values
console.log(mapNumbers([5, 5, 5])); // All become 50
console.log(mapNumbers([])); // Empty array
[ 50, 50, 50 ] []
Conclusion
Normalizing arrays to a 0-100 scale is useful for data visualization and comparison. The key is finding the range and applying proportional scaling to each value.
