Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array in descending order using Lo-Dash?

Tags:

arrays

lodash

I have an array from a push items and when I display using Lo-Dash, it shows in ascending order.

Here's my code:

<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 );
});

Output:

Sorted Array

201508031_aug_3_2015
201511011_nov_1_2015
20151124_nov_24_2015
20160118_jan_18_2016

Now, how can I display this in descending order?

Expected output should be:

20160118_jan_18_2016
20151124_nov_24_2015
201511011_nov_1_2015
201508031_aug_3_2015

Here's the 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>

Appreciate any help on this. Thank you.

like image 706
syntaxcode Avatar asked Dec 15 '25 00:12

syntaxcode


1 Answers

Simple sort the array in ascendent order then reverse it

_.reverse(array)

here is the lodash documentation link _.reverse(array)

like image 135
Piyush Patel Avatar answered Dec 16 '25 21:12

Piyush Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!