Sorting by Count

Hi,

I was wondering if it was possible to sort a bar chart descending by count of entries for each category.
Something like the image below.
image

Thank you.

Dear @jaitsujin,
There are always ways to sort the chart, but how to do it would depend on your chart configuration, whether you have aggregation or not, etc. You can always apply JavaScript code in Advanced section for sorting. You can find different examples for sorting in this article - Configure aggregation and sorting

Thanks for the link. It's somewhat what I'm looking for but not really.
it doesn't matter to me if the chart is aggregated or not, it's a very basic chart that counts items based on a category.
All i need to do is sort by item count per category. highest bein on top.

I have a start but don't know how i would make this work.

var branches = [];
const counts = {};
 
handlers.requestSuccess = function(data, logger) {
    for(var i = 0; i < data.items.length; i++){
        branches.push(data.items[i].Branch); 
    }
    
    var counts = branches.reduce(function(obj, b) {
        obj[b] = ++obj[b] || 1;
        return obj;
    }, {});
  
    let sortable = [];
    for (var vehicle in counts) {
        sortable.push([vehicle, counts[vehicle]]);
    }

    sortable.sort(function(a, b) {
        return a[1] - b[1];
    });
  	sortable.reverse();
     
  	logger.debug(sortable);
  	console.log(sortable);
    
    
    return true;
}

The above will return this:

sorted by the items count.

Is this something that could work? Am I on the right track?

Dear @jaitsujin,
Yes, I think you're on the right track, now you just need to change order of items in data.items and you'll have the correct order that you need.

Hi,
Thanks for the response.

I could use a little help with the data.items. How can i achieve. do you have some samples?

Dear @jaitsujin,
I don't know what your settings are to give a direct answer. This image implies some form of aggregation:
image

In most basic example, I have a list like this:
image

I then render them by Count of items in the same category:

I then use the following code:

var categories = {};

handlers.requestSuccess = function(data, logger) {
  for(var i = 0; i < data.items.length; i++){
    if(categories[data.items[i].Category] == null){
      categories[data.items[i].Category] = 1;
    }
    else{
      categories[data.items[i].Category] += 1;
    }
  }
  var categoriesSorted = Object.keys(categories).sort(function(a,b){return categories[b]-categories[a]})
  data.items.sort(function(a, b) {
      return categoriesSorted.indexOf(a.Category) - categoriesSorted.indexOf(b.Category);
  });

  logger.debug('Categories: ', categories);
  return true;
}

And get the following result:

1 Like

You are a life saver! This work fantastically!!

I was sort of on the right track, but after seeing your approach realized that I was way off.

Thanks again, you saved the day!