
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
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. Means that the greatest number should get replaced by 100, the smallest by 100 and all others should get converted to specific numbers between 0 and 100 according to the ratio.
Following is the code for doing the same −
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
The output in the console will be −
[ 90.71688942891859, 100, 24.59295261239368, 0, 73.02551640340218, 48.74848116646417 ]
Advertisements