简体   繁体   English

如何使用underscore.js sortBy

[英]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 我正在尝试从下划线模板中的json文件重新排列多维数组,以便可以从最高病例数到最低病例数打印出疾病

The problem comes from the sortBy function not actually sorting the arrays. 问题出在sortBy函数没有真正对数组进行排序。

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] totalCases数组看起来像:[163、134、98、118、2、167、152、102、49、4、0、0、0、1、0、0、1265]

And the sortBy function is: 并且sortBy函数是:

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

it returns 163, 134, 98, 118, 2, 167, 152, 102, 49, 4, 0, 0, 0, 1, 0, 0, 1265 它返回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 我不知道我使用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. sortBy文档 ,它需要一个排序标准或属性名称的回调,所以您不希望在其中输出任何内容。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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