0

I am trying to sort an array like below arrange according to frequency, but it seems to be according to alphabetical order now;

https://jsbin.com/kicusixoha/edit?html,js,console,output

const arr = ["apples", "oranges", "oranges", "oranges",
  "bananas", "bananas", "oranges"
];

let counter = arr.reduce(
  (counter, key) => {
    counter[key] = 1 + counter[key] || 1;
    return counter
  }, {});
console.log(counter)

The output above is:

{
  apples: 1,
  bananas: 2,
  oranges: 4
}

but I need it to be like below with the most frequency to be the first:

{
  oranges: 4,
  bananas: 2,
  apples: 1,
}

Any help would be greatly appreciated.

Daryl Wong
  • 2,023
  • 5
  • 28
  • 61
  • 1
    Although you *can* do that now (as of ES2015), it's almost never a good idea. Instead, use an array. If not an array, use a `Map`. The order of properties in objects is complicated. Arrays are simple. :-) Even a `Map`'s order is much simpler than an object's (it's the order in which the entries were created). – T.J. Crowder Oct 20 '20 at 09:40
  • 1
    FWIW, with a `Map`: https://jsfiddle.net/tjcrowder/89nqojvk/ To have an object at the end instead, change the last `new Map` to `Object.fromEntries` -- but again, I don't recommend it, not least because if any of your values are all digits instead of letters, the order won't be right. – T.J. Crowder Oct 20 '20 at 09:46
  • @T.J.Crowder, thx got it... – Daryl Wong Oct 20 '20 at 10:18

0 Answers0