- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Sorting array according to increasing frequency of elements in JavaScript
We are required to write a JavaScript function that takes in an array of literals as the first and the only argument.
The array is likely to contain many repeating values. Our function should sort the array such that the values that are unique or that have the least frequency are placed before the ones that have the most.
For example −
If the input array is −
const arr = [4, 7, 3, 5, 5, 4, 7, 9, 2, 1, 5, 7, 5, 5, 9];
Then the output array should be −
const output = [ 3, 2, 1, 9, 9, 4, 4, 7, 7, 7, 5, 5, 5, 5, 5 ];
Example
Following is the code −
const arr = [4, 7, 3, 5, 5, 4, 7, 9, 2, 1, 5, 7, 5, 5, 9]; const sortByNumbers = (arr = []) => { const map = {}; const res = []; for (let i = 0; i < arr.length; i++) { map[arr[i]] = map[arr[i]] || [0]; map[arr[i]][0]++; map[arr[i]][1] = arr[i]; } const sorted = Object.values(map).sort((a, b) => { if (a[0] === b[0]) { return b[1] - a[1]; } return a[0] - b[0] }); for (let i = 0; i < sorted.length; i++) { const [freq, num] = sorted[i] for (let j = 0; j < freq; j++) { res.push(num); } } return res; }; console.log(sortByNumbers(arr));
Output
Following is the console output −
[ 3, 2, 1, 9, 9, 4, 4, 7, 7, 7, 5, 5, 5, 5, 5 ]
- Related Articles
- Sorting array based on increasing frequency of elements in JavaScript
- Sorting array of Number by increasing frequency JavaScript
- Program to sort array by increasing frequency of elements in Python
- Sorting according to weights of numbers in JavaScript
- Sorting objects according to days name JavaScript
- Sorting numbers according to the digit root JavaScript
- Sort the second array according to the elements of the first array in JavaScript
- Sorting according to number of 1s in binary representation using JavaScript
- Count unique elements in array without sorting JavaScript
- Sorting array of exactly three unique repeating elements in JavaScript
- Sorting an array according to another array using pair in STL in C++
- Sorting string characters by frequency in JavaScript
- Frequency of elements of one array that appear in another array using JavaScript
- Uneven sorting of array in JavaScript
- Building frequency map of all the elements in an array JavaScript

Advertisements