3

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.

2 Answers 2

3

Simple sort the array in ascendent order then reverse it

_.reverse(array)

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

Sign up to request clarification or add additional context in comments.

Comments

1

If your array is sorted in ascending order, and you want the output in descending order, just replace your each() call with eachRight(). This will iterate over the array in the opposite direction.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.