
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements