Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I sort a coffeescript Map object by property value?
    text
    copied!<p>I have a list of <code>articles</code> each of which has a simple string array of <code>Tags</code>. I count the tag frequency like this:</p> <p><strong>Count The Tag Frquency</strong></p> <pre><code>getTags = (articles) -&gt; tags= {} for article in articles for tag in article.Tags tags[tag] = (tags[tag] or 0) + 1 tags </code></pre> <p><strong>Example Result</strong></p> <p>The <code>tags</code> map produced is an object with property names set to the <code>Tag</code> name and property values set to the frequency count, like so:</p> <p><img src="https://i.stack.imgur.com/oXnGb.png" alt="enter image description here"></p> <p><strong>Question</strong></p> <p>I would like to order this list by the property value (the frequency count), how can I achieve this? </p> <p>Note: <em>I am happy to change the counting method if required</em></p> <p><strong>Edit 1</strong></p> <p>Thanks to @LeonidBeschastny I now have working code:</p> <pre><code>getTags = (articles) -&gt; tags = {} for article in articles for tag in article.Tags tags[tag] = (tags[tag] or 0) + 1 tags = do (tags) -&gt; keys = Object.keys(tags).sort (a, b) -&gt; tags[b] - tags[a] {name, count: tags[name]} for name in keys tags </code></pre> <p>You can see that I am having to project the unsorted <code>tags</code> map object into a new array of sorted <code>{name:value}</code> objects. </p> <p>This feels like it is too much work and I think maybe the original unsorted object was a mistake. Is there a way to get to the sorted array without going through this intermediate step?</p> <p><strong>Edit 2</strong></p> <p>Thanks to @hpaulj for doing some time tests and discovering that the code above is actually reasonably efficient compared to other potential solutions, such as a running sorted heap.</p> <p>I have now put this code into production and it is working well.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload