- 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 based on increasing frequency of elements in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.
The array arr, might contain some duplicates. Our function is supposed to sort the array in such a way that the elements that appear for least number of times are placed first followed by elements in increasing frequency.
If two elements appear for the same number of times in the array then they should be placed in increasing order.
For example, if the input to the function is
Input
const arr = [5, 4, 5, 4, 2, 1, 12];
Output
const output = [1, 2, 12, 4, 4, 5, 5];
Output Explanation
The numbers 1, 2 and 12 all appear once hence sorted in increasing order and then 4 and 5 both appear twice.
Example
Following is the code −
const arr = [5, 4, 5, 4, 2, 1, 12]; const sortByAppearance = (arr = []) => { arr.sort((a, b) => a - b); const res = []; const searched = {}; const countAppearance = (list, target) => { searched[target] = true; let count = 0; let index = list.indexOf(target); while(index !== -1){ count++; list.splice(index, 1); index = list.indexOf(target); }; return count; }; const map = []; arr.forEach(el => { if(!searched.hasOwnProperty(el)){ map.push([el, countAppearance(arr.slice(), el)]); }; }); map.sort((a, b) => a[1] - b[1]); map.forEach(([num, freq]) => { while(freq){ res.push(num); freq--; } }); return res; }; console.log(sortByAppearance(arr));
Output
[1, 2, 12, 4, 4, 5, 5]
- Related Articles
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting array of Number by increasing frequency JavaScript
- Sorting Array based on another array JavaScript
- Program to sort array by increasing frequency of elements in Python
- Constructing an array of smaller elements than the corresponding elements based on input array in JavaScript
- Sorting numbers based on their digit sums in JavaScript
- Encoding string based on character frequency in JavaScript
- Count unique elements in array without sorting JavaScript
- Sorting array of exactly three unique repeating elements in JavaScript
- Sort array based on another array in JavaScript
- Filter array based on another array in JavaScript
- Sorting string characters by frequency in JavaScript
- Frequency of elements of one array that appear in another array using JavaScript
- Sorting string of words based on the number present in each word using JavaScript
- Reorder array based on condition in JavaScript?

Advertisements