0

I am trying to sort the array of letters by their frequency of use. but not getting the correct output. here is my try:

const ar = ['b', 'c', 'a', 'a', 'a', 'e', 'e', 'e', 'e', 'c'];

const re = ar.reduce((ar, l) => {
  ar[l] ? ar[l]++ : (ar[l] = 1); //finding count of each instance
  return ar;
}, {});

const vls = [];

for (const [key, val] of Object.entries(re)) {
  for (let i = 0; i < val; i++) {
    vls.push(key); //re creating array by thier count
  }
}

const sr = vls.sort((a, i) => (a < i ? 1 : -1)); //not works
console.log(sr);

//out put should be letters frequecy ['e', 'e', 'e', 'e','a', 'a', 'a','c','c','b]

Any short and quick way to go? Thanks in advance.

Simone Rossaini
  • 7,192
  • 1
  • 9
  • 28
3gwebtrain
  • 14,377
  • 24
  • 102
  • 222
  • See [Sort Array by Element Frequency JavaScript](/q/69575564/4642212). Why are you recreating the array? You lose all frequency information this way. Sort `Object.entries(re)` instead using [JavaScript: Sort an array of objects by a numeric property in each object](/q/54623130/4642212) (the property you’re looking for is `1`), _then_ recreate the array. – Sebastian Simon Feb 11 '22 at 14:23
  • After the `reduce` just: `ar.sort((a,b) => re[b] - re[a])` – adiga Feb 11 '22 at 14:30
  • `array.sort(function(a,b){ a = array.filter(x => x === a).length; b = array.filter(x => x === b).length; return b - a; });` – cmgchess Feb 11 '22 at 14:33

0 Answers0