如何使用Lo-Dash将数组按降序排序?

3

我有一个数组,其中包含推送的项目,当我使用Lo-Dash显示时,它以升序显示。

这是我的代码:

<h3>Sorted Array</h3>
<ul id="sorted"></ul>

// Sample array.
var array = [];

// Utility function used to push data into the
// array while maintaining the sort order.
function sortedPush( array, value ) {
    array.splice( _.sortedIndex( array, value ), 0, value );
}

// push items.
sortedPush( array, "20151124_nov_24_2015" );
sortedPush( array, "201511011_nov_1_2015" );
sortedPush( array, "20160118_jan_18_2016" );
sortedPush( array, "201508031_aug_3_2015" );

// The ul for output.
var list = document.getElementById( "sorted" );

// Display the sorted array.
_.each( array, function( item ) {
    var li = document.createElement( "li" );
    li.appendChild( document.createTextNode( item ) );
    list.appendChild( li );
});

输出:

已排序的数组

201508031_aug_3_2015
201511011_nov_1_2015
20151124_nov_24_2015
20160118_jan_18_2016

现在,如何按降序显示它?

期望的输出应该是:

20160118_jan_18_2016
20151124_nov_24_2015
201511011_nov_1_2015
201508031_aug_3_2015

这里是 fiddle - https://jsfiddle.net/vLvv6ogf/1/

// Sample array.
var array = [];

// Utility function used to push data into the
// array while maintaining the sort order.
function sortedPush(array, value) {
  array.splice(_.sortedIndex(array, value), 0, value);
}

// push items.
sortedPush(array, "20151124_nov_24_2015");
sortedPush(array, "201511011_nov_1_2015");
sortedPush(array, "20160118_jan_18_2016");
sortedPush(array, "201508031_aug_3_2015");


// The ul for output.
var list = document.getElementById("sorted");

// Display the sorted array.
_.each(array, function(item) {
  var li = document.createElement("li");
  li.appendChild(document.createTextNode(item));
  list.appendChild(li);
});
<h3>Sorted Array</h3>
<ul id="sorted"></ul>

感激任何关于此事的帮助。谢谢。
2个回答

3

将数组按升序排序,然后反转它。

_.reverse(array)

这是lodash的文档链接 _.reverse(array)


1
如果你的数组按升序排序,并且想要输出按降序排列的结果,只需将 each() 调用替换为 eachRight()。这将沿着相反的方向迭代数组。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接