Sorting array of Number by increasing frequency JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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];

Example

const arr = [1, 1, 2, 2, 2, 3];
const frequencySort = (arr = []) => {
   let map = {};
   for (let i = 0; i < arr.length; i++) {
      map[arr[i]] = (map[arr[i]] || 0) + 1;
   };
   return arr.sort((a,b) => map[a] - map[b] || b - a);
};
frequencySort(arr);
console.log(arr);

Output

This will produce the following output −

[ 3, 1, 1, 2, 2, 2 ]
raja
Published on 25-Nov-2020 05:14:02
Advertisements