1

I have used the JavaScript .forEach method to iterate through a given array of characters to return an object that indicates the character and the number of times the character occurs:

var textArray = [a, b, b, c, d, e, e, e, f];

var count = {};

textArray.forEach(function(elem) {
    count[elem] = count[elem] + 1 || 1;
});

console.log(count);

Would log:

{
a: 1,
b: 2,
c: 1,
d: 1,
e: 3,
f: 1
}

How can I then sort the object by descending occurrence? i.e.:

{
e: 3,
b: 2,
a: 1,
c: 1,
d: 1,
f: 1
}
CharStar
  • 427
  • 1
  • 6
  • 24

1 Answers1

0

You can do this like this.

function sort_object(list){
  var sorted_list= new Object();
  var sorted_keys=Object.keys(list)
                          .sort((b,a) => list[a]-list[b]);
  sorted_keys.forEach(function(val){
            sorted_list[val]=list[val];
  });
  
  return sorted_list;
}


var data = {a: 1, b: 2, c: 1, d: 1, e: 3};

console.log(sort_object(data));
Nadir Laskar
  • 4,012
  • 2
  • 16
  • 33