Frequency-based Array Sorting in JavaScript
The function sortByFrequency()
takes an array as an input and performs the following steps:
- It creates an empty object called
frequency
. This object will be used to store the frequency of each element in the array. - It then iterates over the input array using a for loop. For each element in the array, it checks if an entry for that element already exists in the
frequency
object. If it does, it increments the count by 1. If not, it creates a new entry for that element with a count of 1. - After counting the frequency of each element, the function uses the
sort()
method to sort the input array. Thesort()
method takes a comparison function as an argument, which is used to determine the sort order of the elements. In this case, the comparison function compares the frequency of each element in thefrequency
object. Specifically, it returns the difference between the frequency of elementb
and elementa
. If the difference is positive, elementb
will be placed before elementa
in the sorted array. If the difference is negative, elementa
will be placed before elementb
. If the difference is 0, the order of the elements will not change. - The function then returns the sorted array, where elements with higher frequency appear before elements with lower frequency.
In the example you provided, the input array is [3, 1, 2, 2, 1, 3, 4, 4, 4], the function will create an object frequency
that contains:
frequency = {3:2, 1:2, 2:2, 4:3}
After that, the array will be sorted based on the frequency of each element in the frequency object, and the output will be [4, 4, 4, 1, 1, 2, 2, 3, 3].
Here's an example of a function in JavaScript that sorts the elements of an array by their frequency of occurrence:
function sortByFrequency(arr) {// Create an object to store the frequency of each elementvar frequency = {};// Iterate over the array and count the frequency of each elementfor (var i = 0; i < arr.length; i++) {var element = arr[i];if (frequency[element]) {frequency[element]++;} else {frequency[element] = 1;}}// Sort the array based on the frequency of each elementreturn arr.sort(function(a, b) {return frequency[b] - frequency[a];});}console.log(sortByFrequency([3, 1, 2, 2, 1, 3, 4, 4, 4]));
This will output: [4, 4, 4, 1, 1, 2, 2, 3, 3]
Explanation:
The function takes an array and create an object frequency
that stores the frequency of each element in the array. Then it iterates over the array and counts the frequency of each element. Finally, it sorts the array based on the frequency of each element using the sort()
method and a comparison function which compares the frequency of each element in the frequency object.
Comments
Post a Comment