Normalize numbers in an object - JavaScript


Suppose, we have an object with strings mapped to numbers like this −

const obj = {
   num1: 45,
   num2: 78,
   num3: 234,
   num4: 3,
   num5: 79,
   num6: 23
};

We are required to write a JavaScript function that takes in one such object as the first argument and an array of strictly two numbers as the second argument.

The second argument basically represents a range −

[a, b] (b >= a)

Our job is to normalize the object values according to the range.

Therefore, the largest value of the object must become b and the smallest must become a. And others lying between should be adjusted accordingly.

Example

Following is the code −

const obj = {
   num1: 45,
   num2: 78,
   num3: 234,
   num4: 3,
   num5: 79,
   num6: 23
};
const range = [10, 15];
const normaliseObject = (obj, range) => {
   const values = Object.values(obj);
   const min = Math.min.apply(Math, values);
   const max = Math.max.apply(Math, values);
   const variation = (range[1] - range[0]) / (max - min);
   Object.keys(obj).forEach(el => {
      const val = (range[0] + ((obj[el] - min) * variation)).toFixed(2);
      obj[el] = +val;
   });
};
normaliseObject(obj, range);
console.log(obj);

Output

This will produce the following output in console −

{
   num1: 10.91,
   num2: 11.62,
   num3: 15,
   num4: 10,
   num5: 11.65,
   num6: 10.43
}

Updated on: 18-Sep-2020

431 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements