Sorting array based on increasing frequency of elements in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.

The array arr, might contain some duplicates. Our function is supposed to sort the array in such a way that the elements that appear for least number of times are placed first followed by elements in increasing frequency.

If two elements appear for the same number of times in the array then they should be placed in increasing order.

For example, if the input to the function is

Input

const arr = [5, 4, 5, 4, 2, 1, 12];

Output

const output = [1, 2, 12, 4, 4, 5, 5];

Output Explanation

The numbers 1, 2 and 12 all appear once hence sorted in increasing order and then 4 and 5 both appear twice.

Example

Following is the code −

 Live Demo

const arr = [5, 4, 5, 4, 2, 1, 12];
const sortByAppearance = (arr = []) => {
   arr.sort((a, b) => a - b);
   const res = [];
   const searched = {};
   const countAppearance = (list, target) => {
      searched[target] = true;
      let count = 0;
      let index = list.indexOf(target);
      while(index !== -1){
         count++;
         list.splice(index, 1);
         index = list.indexOf(target);
      };
      return count;
   };

   const map = [];
   arr.forEach(el => {
      if(!searched.hasOwnProperty(el)){
         map.push([el, countAppearance(arr.slice(), el)]);
      };
   });
   map.sort((a, b) => a[1] - b[1]);

   map.forEach(([num, freq]) => {
      while(freq){
         res.push(num);
         freq--;
      }
   });
   return res;
};
console.log(sortByAppearance(arr));

Output

[1, 2, 12, 4, 4, 5, 5]

Updated on: 24-Apr-2021

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements