简体   繁体   中英

How to use underscore.js sortBy

I'm trying to rearrange a multidimensional array from a json file in my underscore template so that I can print out the disease from highest # of cases to lowest # of cases

The problem comes from the sortBy function not actually sorting the arrays.

here is an example Array that I'm working with

The totalCases array looks like: [163, 134, 98, 118, 2, 167, 152, 102, 49, 4, 0, 0, 0, 1, 0, 0, 1265]

And the sortBy function is:

 <% _.sortBy(totalCases , function (num) { %>
    <%= num %>
 <% }); %>

it returns 163, 134, 98, 118, 2, 167, 152, 102, 49, 4, 0, 0, 0, 1, 0, 0, 1265

I don't know what is going wrong with how I'm using the sortBy

You are mixing view with controller somehow. You don't want to rearrange the array in the underscore template, but before presenting it. Reread the docs for sortBy , it takes a callback for the sort criteria or a property name or so, you don't want to output anything in there.

<%  var sortedCases = _.sortBy(totalCases, function(case) {
        return // your sort criteria here, e.g. `case.occurences`
    });
%><ol><%
    _.each(sortedCases, function(case) { %>
        <li><%= case /* … */ %></li>
<%  } %></ol>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM