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

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 ]

Updated on: 25-Nov-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements