Normalize numbers to a 0-1 range in JavaScript
Intermediate · 4 min read
Sensor readings, prices and test scores all come on different scales. Temperatures might run from 12 to 60, prices from 500 to 90,000. To compare them, draw them on the same chart, or feed them to a machine learning model, you often squeeze each list onto the same range: 0 for the smallest value and 1 for the largest. This is called min-max normalization.
In this tutorial you will normalize a list of readings, stretch it onto any range you like (such as 0 to 100 for percentages), turn it back into the original readings, and see what happens when every reading is the same. You need to know arrays, map and arrow functions.
The idea in one line
Take a reading x. Subtract the smallest value, lo, so the smallest becomes 0. Then divide by the span, hi - lo, so the largest becomes 1:
t = (x - lo) / (hi - lo)
For the readings 12, 40, 25 and 60, lo is 12 and hi is 60, so the span is 48. The reading 40 becomes (40 - 12) / 48 = 28 / 48, which is about 0.5833. It sits a bit more than halfway between the smallest and the largest.
Finding the smallest and largest
Math.min and Math.max take separate numbers, not an array. The spread syntax ... unpacks an array into separate arguments:
const readings = [12, 40, 25, 60];
console.log(Math.min(...readings)); // 12
console.log(Math.max(...readings)); // 60
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
63 Normalising a list to 0 and 1
fairRescale readings so the smallest becomes 0 and the largest becomes 1. Then rescale to an arbitrary range, invert the transform, and show what a list of identical readings does to it.
Stuck? Three hints, smallest first
- 1.
(x - min) / (max - min)is the whole transform. - 2. The two ends must come out as exactly 0 and exactly 1.
- 3. If every reading is the same,
max - minis 0 and every result is0 / 0.
Step 1: normalize
function normalise(xs) {
const lo = Math.min(...xs);
const hi = Math.max(...xs);
return xs.map((x) => (x - lo) / (hi - lo)); // 0 / 0 when hi === lo
}
const unit = normalise(readings);
console.log(unit); // [ 0, 0.5833333333333334, 0.2708333333333333, 1 ]
The function keeps the answer's spelling, normalise. We find lo and hi once, outside map, so they are not worked out again for every reading. The order of the list stays the same: the first reading, 12, becomes 0, and the last, 60, becomes 1.
Step 2: round for display
The middle values have long tails of digits. A small helper rounds to four decimal places for printing:
const round4 = (x) => Math.round(x * 10000) / 10000;
console.log(unit.map(round4)); // [ 0, 0.5833, 0.2708, 1 ]
console.log(unit[0], unit[3]); // 0 1
The two ends come out as exactly 0 and exactly 1, and that is guaranteed: lo - lo is always 0, and (hi - lo) / (hi - lo) is always 1. Only the middle values are approximate.
Normalizing also keeps the order: 60 was the largest reading and 1 is the largest result, 40 is still above 25, and so on.
Step 3: back to the original readings
Undoing the transform is the same sum run backwards: multiply by the span, then add lo.
const denormalise = (ts, lo, hi) => ts.map((t) => lo + t * (hi - lo));
console.log(denormalise(unit, 12, 60)); // [ 12, 40, 25, 60 ]
We got the original readings back, exactly. That was partly luck: the span 48 is 3 × 16, and dividing then multiplying by it happens not to lose any bits here. With other spans the round trip can come back a tiny bit out, so compare with a small tolerance rather than ===.
Step 4: any range, not just 0 to 1
Once you have values from 0 to 1, moving them to any range from a to b is one more step: start at a and go t of the way to b.
const rescale = (xs, a, b) => normalise(xs).map((t) => a + t * (b - a));
console.log(rescale(readings, 20, 80)); // [ 20, 55, 36.25, 80 ]
console.log(rescale(readings, 0, 100).map(round4)); // [ 0, 58.3333, 27.0833, 100 ]
The 0 to 100 version reads as a percentage of the span: the reading 40 is about 58% of the way from the lowest reading to the highest.
Step 5: when every reading is the same
Now try a sensor that has not moved:
const flat = [7, 7, 7];
console.log(normalise(flat)); // [ NaN, NaN, NaN ]
console.log(normalise(flat)[0] === 0); // false
Here lo and hi are both 7, so the span is 0, and every result is 0 / 0, which is NaN (Not a Number). JavaScript doesn't throw an error. It hands back NaN quietly, and NaN spreads: into a chart it becomes a missing bar, into JSON it becomes null, and any sum that touches it becomes NaN too.
The fix is to decide what a flat list means for your app, usually all 0 or all 0.5, and return that yourself:
function safeNormalise(xs) {
const lo = Math.min(...xs);
const hi = Math.max(...xs);
if (hi === lo) return xs.map(() => 0);
return xs.map((x) => (x - lo) / (hi - lo));
}
console.log(safeNormalise(flat)); // [ 0, 0, 0 ]
The full solution
The answer panel has normalise, rescale and denormalise, and prints the normalized readings, the rounded values, the two ends, the round trip, the 20 to 80 and percentage versions, and the flat list. Press Run to see the output.
function normalise(xs) {
const lo = Math.min(...xs);
const hi = Math.max(...xs);
return xs.map((x) => (x - lo) / (hi - lo)); // 0 / 0 when hi === lo
}
const rescale = (xs, a, b) => normalise(xs).map((t) => a + t * (b - a));
const denormalise = (ts, lo, hi) => ts.map((t) => lo + t * (hi - lo));
const readings = [12, 40, 25, 60];
const flat = [7, 7, 7];
const unit = normalise(readings);
const round4 = (x) => Math.round(x * 10000) / 10000;
console.log('normalised :', unit);
console.log('to 4 places:', unit.map(round4));
console.log('ends :', unit[0], unit[3]);
console.log('back again :', denormalise(unit, 12, 60));
console.log('to 20..80 :', rescale(readings, 20, 80));
console.log('as percent :', rescale(readings, 0, 100).map(round4));
console.log('flat list :', normalise(flat));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the smallest reading becomes exactly 0 and the largest exactly 1', [unit[0], unit[3]], [0, 1]);
test('the two in between, to four places', unit.map(round4), [0, 0.5833, 0.2708, 1]);
test('the transform is order-preserving', [unit[3] > unit[1], unit[1] > unit[2], unit[2] > unit[0]], [true, true, true]);
test('and it inverts back to the original readings, exactly this time', denormalise(unit, 12, 60), readings);
test('rescaling to 20..80 is the same map with different ends', rescale(readings, 20, 80), [20, 55, 36.25, 80]);
test('rescaling to 0..100 gives percentages of the span', rescale(readings, 0, 100).map(round4), [0, 58.3333, 27.0833, 100]);
test('a list of identical readings divides by zero, so every result is NaN', normalise(flat).every(Number.isNaN), true);
test('which is not the same as every result being 0', normalise(flat)[0] === 0, false);
Min-max normalisation is one subtraction and one division, and the whole risk is in the denominator. Identical readings — a sensor that has not moved, a single row, a column of one repeated value — make max - min zero, and every output becomes NaN. That NaN then travels: into a chart as a missing bar, into JSON as null, into a model as a poisoned feature. Decide what a flat list means, usually 0 or 0.5, and return it explicitly.
The exact 0 and 1 at the ends are not luck: (lo - lo) is 0 and (hi - lo) / (hi - lo) is 1 for any finite values, so the endpoints are safe even when the middle is not. Round-tripping through denormalise happened to be exact here because 48 is a power of two times 3; with other spans it will be a bit out, so compare with a tolerance rather than ===.
Common mistakes
- Dividing by
hiinstead ofhi - lo. That only works when the smallest value is 0. For our readings it would give 0.2 for the smallest, not 0. - Ignoring the flat list. When every value is the same, the span is 0 and every result is
NaN. Check for it. - Calling
Math.min(readings)without the spread. Passing the array itself givesNaNfor a list likereadings. WriteMath.min(...readings).
Try it yourself
- Normalize the prices
[500, 1200, 90000, 4500]. Which one ends up closest to 0? - Write
rescaleSafe(xs, a, b)that usessafeNormalise, so a flat list comes back as alla. - Normalize
[3, 9, 6], thendenormaliseit with the rightloandhi, and check each value against the original withMath.abs(x - y) < 1e-9.