Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Sorting array of Number by increasing frequency 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];
How It Works
The solution involves two steps:
- Count the frequency of each element using a frequency map
- Sort the array by frequency (ascending) and by value (descending) for ties
Example
const arr = [1, 1, 2, 2, 2, 3];
const frequencySort = (arr = []) => {
let map = {};
// Count frequency of each element
for (let i = 0; i map[a] - map[b] || b - a);
};
const result = frequencySort([...arr]); // Create copy to avoid modifying original
console.log("Original array:", arr);
console.log("Sorted array:", result);
Frequency map: { '1': 2, '2': 3, '3': 1 }
Original array: [ 1, 1, 2, 2, 2, 3 ]
Sorted array: [ 3, 1, 1, 2, 2, 2 ]
Step-by-Step Breakdown
const arr = [4, 4, 2, 2, 2, 1, 1, 1, 1];
const frequencySort = (arr = []) => {
let map = {};
// Step 1: Build frequency map
for (let i = 0; i {
const freqDiff = map[a] - map[b];
if (freqDiff !== 0) {
return freqDiff; // Sort by frequency (ascending)
}
return b - a; // If same frequency, sort by value (descending)
});
};
const result = frequencySort([...arr]);
console.log("Result:", result);
Frequencies: 4: appears 2 times 2: appears 3 times 1: appears 4 times Result: [ 4, 4, 2, 2, 2, 1, 1, 1, 1 ]
Key Points
- Frequency Map: Uses an object to count occurrences of each element
-
Sort Logic:
map[a] - map[b]sorts by frequency (ascending) -
Tie Breaking:
b - asorts by value (descending) when frequencies are equal - In-Place Sorting: The original array is modified unless you create a copy
Conclusion
This approach efficiently sorts arrays by frequency using a frequency map and custom comparator. Elements with lower frequencies appear first, making it useful for data analysis and prioritization tasks.
Advertisements
