-2

Need to create a custom sort for an array --

-- first separate numbers by frequency --- subset numbers of having frequency 1 --- subset numbers of having frequency 2

partially sorted data - with respect to asc order of frequency - then we sort each subset of elements of having the same frequencey in non desc order

function cSort(arr) {
    if(typeof arr !== "undefined") {
        arr.sort(function(a, b) {
          return a - b;
        });

        return arr
    }
}

needs to satisfy the test cases

-- test 1 input [5, 3, 1, 2, 2, 4] output [1, 3, 4, 2, 2]

-- test 2 input [10, 8, 5, 5, 5, 5, 1, 1, 1, 4, 4] output [8, 4, 4, 1, 1, 1, 5, 5, 5, 5]

-- current jsfiddle 1 http://jsfiddle.net/6mekdn8h/

new fiddle 2 http://jsfiddle.net/6mekdn8h/1/

The Old County
  • 89
  • 13
  • 59
  • 129

1 Answers1

1

You could take a sorting with the count of the occurences of each item.

var array = [5, 3, 1, 2, 2, 4].slice(1),
    hash = array.reduce((h, v, i) => (h[v] = (h[v] || 0) + 1, h), {});

array.sort((a, b) => hash[a] - hash[b] || a - b);

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392