- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting How Many Numbers Are Smaller Than the Current Number in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers.
The function should construct a new array based on the input array.
Each corresponding element of the new array should be the number of elements that are smaller in the original array than that corresponding element.
For example −
If the input array is −
const arr = [2, 7, 3, 1, 56, 4, 7, 8];
Then the output array should be −
const output = [1, 4, 2, 0, 7, 3, 4, 6 ];
Example
Following is the code −
const arr = [2, 7, 3, 1, 56, 4, 7, 8]; const smallerThanCurrent = (arr = []) => { let { length } = arr; let res = Array(length).fill(0); for (let i = 0; i < length; i++){ for (let j = 0; j < length; ++j){ if (i != j && arr[i] > arr[j]){ ++res[i]; }; }; }; return res; }; console.log(smallerThanCurrent(arr));
Output
Following is the console output
[ 1, 4, 2, 0, 7, 3, 4, 6 ]
Advertisements