How to use an Object In Javascript
Initialize an empty object to store the frequency of each number. Iterate through the array and count the frequency of each number. Sort the array based on increasing frequency using a custom comparator function. If two numbers have different frequencies, sort them based on their frequencies in ascending order. If two numbers have the same frequency, sort them based on their values in ascending order. Return the sorted array.
Example: Demonstration of Sorting array of Numbers by increasing frequency in JavaScript using an Object.
function sortIncreasFreq(arr) {
const freqMap = {};
arr.forEach(num => {
freqMap[num] =
(freqMap[num] || 0) + 1;
});
return arr.sort((a, b) => {
if (freqMap[a] !== freqMap[b]) {
return freqMap[a] - freqMap[b];
} else {
return a - b;
}
});
}
const arr = [3, 3, 1, 1, 1, 8, 3, 6, 8, 8];
console.log("Sorted by increasing frequency:",
sortIncreasFreq(arr));
Output
Sorted by increasing frequency: [ 6, 1, 1, 1, 3, 3, 3, 8, 8, 8 ]
Time Complexity: O(n log n)
Space Complexity: O(n)
Sorting Array of Number by Increasing Frequency using JavaScript
To sort an array of given numbers based on the frequency of occurrence of each number first sort the array such that the elements repeated for the least number of times appear first followed by the elements with increasing frequency.
Example:
Input:
array = [3, 3, 1, 1, 1, 8, 3, 6, 8, 8]
Output:
[6, 1, 1, 1, 3, 3, 3, 8, 8, 8]
Explanation:
Number 6 occurs 1 time
Number 1 occurs 3 times
Number 3 occurs 3 times
Number 8 occurs 3 times
Below are the approaches to sort an array of Numbers by increasing frequency using JavaScript:
Table of Content
- Using an Object
- Using Map