1

I have the following function executed as my datatable initiates. It grabs all the keywords in the column "keywords", counts them, and then lists them.

What I want to know is how can I sort the final counts variable by value before I pass it to the html.

function getTags(table) {

var data = $('#mytable').DataTable().rows({search: 'applied'}).data();

var keys=[]; // Get keywords
  for(var i=0;i<data.length;i++){
  keys.push(data[i].keyword)
}   

var keyStr = keys.toString().split(","); // Split keywords

var keyStr = keyStr.filter(function(n){ return n != "" });  // Filter empty      

var counts = {}; // Count unique
for (var i = 0; i < keyStr.length; i++) {
  counts[keyStr[i]] = 1 + (counts[keyStr[i]] || 0);
}

$.each(counts, function (key,value) { // Print list   
  $("#tags ul").append("<li>" + value + key + "</li>");
})
east1999
  • 199
  • 5
  • 15
  • Possible duplicate of [sorting javascript object by property value](https://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value) – SolidCanary Feb 09 '18 at 16:32

1 Answers1

1

You should be able to just use Array.prototype.sort().

counts.sort();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Scath
  • 3,777
  • 10
  • 29
  • 40
  • In this case there's an error: `TypeError: counts.sort is not a function. (In 'counts.sort()', 'counts.sort' is undefined)` . I think it has to do with counts not being an array, but I'm not sure? I added it before `$.each` – east1999 Feb 09 '18 at 16:25
  • What is counts then? Can what if you change the declaration to var counts= []; – Scath Feb 09 '18 at 16:27
  • If I do that, then it returns absolutely nothing. – east1999 Feb 09 '18 at 16:31
  • It looks like `counts` is a single object with multiple attributes. Maybe you should sort the array before counting: `var keyStr = keyStr.filter(function(n){ return n != "" }).sort();` – K Thorngren Feb 09 '18 at 17:04
  • That improves the overall sorting, but the fact is, only `counts` produces the `value` I want to sort the list by. Does this make sense? Only after `counts` do I know how many times do I have keyword X. – east1999 Feb 09 '18 at 17:23
  • I see, you want to sort by the count value not the name. In that case I think the best option is to take your `counts` object and convert it to an array of objects that can then be sorted by the value. This [SO post](https://stackoverflow.com/a/11352763/7764175) looks like a good option to me. – K Thorngren Feb 09 '18 at 19:46