The project uses backbone + underscore and jade + stylus.

There is a variable in the jade template that displays an unsorted list.

<% _.each(territory_list, function(territory) {%> 

To display the list, use the _.each method.

If I understand correctly, to display a sorted list, it is necessary to use the _.sortBy method for the territory_list displayed list. But I do not understand where this method is applied. Imagine that the record should be something like this (does not work):

 <% _.each_.sortBy(territory_list, function(territory) {%> 

How to display a sorted list using the method from underscore?

UPD

I clarify the question. As a result of sorting the list should be displayed in ascending order. For example:

 Территория 1 Территория 2 Территория 3 ... Территория 20 

etc.

  • _.sortBy assumes sorting by some parameter (or using an iterator function). Hence the question: what are the territory_list elements and what is the logic of their sorting. - Dmitriy Simushev
  • territory_list is - as I wrote in the question - a list, i.e. <ul><li></li></ul> ... - Marina Voronova
  • And how do you want to sort it? This is already html, right? - Dmitriy Simushev
  • sort ascending, i.e. from 1 to 20, etc., there is a text and a number, for example: Территория 1 - Marina Voronova
  • Once again: if the territory_list elements are strings with html, then no 1 and 20 anymore. - Dmitriy Simushev

1 answer 1

I don’t know where your views came from, but they are absolutely not true (just glance briefly at Underscore.js documentation to make sure of this).

Moreover, the _.sortBy method _.sortBy needed not to sort arrays of strings, but to sort collections (arrays of the same type). The Array.prototype.sort method is much better suited for sorting an array of strings. But there is one subtlety: this method uses the lexicographical order of lines when sorting. That is, you will receive:

 Foo 1 Foo 10 Foo 2 

instead

 Foo 1 Foo 2 Foo 10 

To get the right result, you need to use natural sorting instead of lexicographic. In general, the task requires separate consideration and may require the use of third-party libraries (for example, javascript-natural-sort , but Google will tell you about others that may be better / more convenient).

If everything is really as simple as you say in the question (a combination of the word " Territory " and its integer number), then you just need to pass the correct comparator function to the Array.prototype.sort method:

 var territoryComparator = function(a, b) { var numRegExp = /(.*?)(\d+)$/; return parseInt(a.replace(numRegExp, '$2')) - parseInt(b.replace(numRegExp, '$2')) }; 

In this case, your template should look like:

 <% _.each(territory_list.sort(territoryComparator), function(territory) { %> <!-- А здесь вы можете отрисовывать ваши "территории" --> <% }) %>