
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
Sort Array of Numbers by Increasing Frequency in JavaScript
We are required to write a JavaScript function that takes in an array of numbers that might contain some repeating numbers.
The function should sort the array such that the elements that are repeated for the least number of times appears first followed by the elements with increasing frequency.
For example −
If the input array is −
const arr = [1,1,2,2,2,3];
Then the sorted array should be −
const output = [3,1,1,2,2,2];
Example
const arr = [1, 1, 2, 2, 2, 3]; const frequencySort = (arr = []) => { let map = {}; for (let i = 0; i < arr.length; i++) { map[arr[i]] = (map[arr[i]] || 0) + 1; }; return arr.sort((a,b) => map[a] - map[b] || b - a); }; frequencySort(arr); console.log(arr);
Output
This will produce the following output −
[ 3, 1, 1, 2, 2, 2 ]
Advertisements