Sorting Array of Number by Increasing Frequency using JavaScript
Last Updated :
17 May, 2024
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:
Using an Object
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.
JavaScript
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));
OutputSorted by increasing frequency: [
6, 1, 1, 1, 3,
3, 3, 8, 8, 8
]
Time Complexity: O(n log n)
Space Complexity: O(n)
Using Map
Initialize an empty Map to store the frequency of each number. Iterate through the array and update 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 Map.
JavaScript
function sortInFreq(arr) {
const freqMap = new Map();
arr.forEach(num => {
freqMap.set(num,
(freqMap.get(num) || 0) + 1);
});
return arr.sort((a, b) => {
if (freqMap.get(a) !== freqMap.get(b)) {
return freqMap.get(a)
- freqMap.get(b);
} else {
return a - b;
}
});
}
const arr = [3, 3, 1, 1, 1, 8, 3, 6, 8, 8];
console.log("Sorted by increasing frequency using Map :",
sortInFreq(arr));
OutputSorted by increasing frequency using Map : [
6, 1, 1, 1, 3,
3, 3, 8, 8, 8
]
Time Complexity: O(n log n)
Space Complexity: O(n)
Similar Reads
Generate Random Number in Given Range Using JavaScript Here are the different ways to generate random numbers in a given range using JavaScript1. Using Math.random(): basic ApproachThis is the simplest way to generate a random number within a range using Math.random().JavaScriptlet min = 10; let max = 20; let random = Math.floor(Math.random() * (max - m
3 min read
Find Mode of an Array using JavaScript To find the mode in an array with JavaScript, where the mode is the number occurring most frequently. Various approaches can be employed to find the mode, and an array may have multiple modes if multiple numbers occur with the same highest frequency. Example:Input:3, 6, 4, 6, 3, 6, 6, 7 , 6, 3 , 3Ou
4 min read
JavaScript - Sort a String Alphabetically using a Function Here are the various methods to sort a string alphabetically using a function in JavaScript.1. Using split(), sort(), and join() MethodsThis is the most basic and commonly used method to sort a string alphabetically. The string is first converted into an array of characters, sorted, and then joined
2 min read
Count Frequency of an Array Item in JavaScript Here are the different approaches to count the frequency of an Array Item in JavaScriptUsing a Loop and CounterThis is the most basic and efficient approach when you want to find the frequency of a single item. You simply loop through the array and count how many times the item appears.JavaScriptcon
2 min read
Sort An Array Of Arrays In JavaScript The following approaches can be used to sort array of arrays in JavaScript.1. Using array.sort() Method- Mostly UsedJS array.sort() is used to sort and update the original array in ascending order.JavaScriptlet arr = [[3, 2], [1, 4], [2, 5], [2, 0]]; arr.sort(); console.log(arr);Output[ [ 1, 4 ], [
2 min read
How to sort element by numerical value of data attribute using JavaScript ? The task is to sort numeric data attributes, there are many ways to sort the HTML elements by the numerical value of data attributes with the help of JavaScript. In this article, we will explain popular and less time-consuming ones.Examples of Sort Elements by Numerical ValueExample 1: Using Dataset
2 min read
JavaScript- Count Frequencies in an Array These are the following ways to count the frequency:1. Using Object (Efficient for Small to Moderate Arrays)We use JavaScript Objects to store frequencies, we iterate over the array using the forEach() method. For each element, we check if the element already exists as a key in the res object. If it
2 min read
Javascript Program for Range Queries for Frequencies of array elements Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type. Examples: Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; lef
2 min read
How to Sort JSON Array in JavaScript by Value ? Sorting is the process of arranging elements in a specific order. In JavaScript, you can sort a JSON array by value using various methods as listed and discussed below with their practical implementation. Table of Content Using sort() FunctionUsing Array.prototype.reduce()Using Bubble SortUsing sort
3 min read
JavaScript - Sort an Array of Strings Here are the various methods to sort an array of strings in JavaScript1. Using Array.sort() MethodThe sort() method is the most widely used method in JavaScript to sort arrays. By default, it sorts the strings in lexicographical (dictionary) order based on Unicode values.JavaScriptlet a = ['Banana',
3 min read