-5

I am new to Javascript and jquery.I want to arrange the date from items[] array to item1[] and item2[] array in ascending and descending order.

var items = ["01-Jun-17", "03-Jun-17", "03-May-17", "05-Jun-17", "05-Jun-17", "18-May-17"];

    Output:
    /*----logic for Ascending:::------ *\
    var item1=["03-May-17","18-May-17","01-Jun-17","03-Jun-17","05-Jun-17","05-Jun-17"];

    /*----- logic for  Descending:::------ *\
    var item2=["05-Jun-17","05-Jun-17","03-Jun-17","01-Jun-17","18-May-17","03-May-17"];
  • 4
    Great, do that. Research it. [Search for previous questions about it.](/help/searching) And make your title and question relate to one another. More in the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Normally I'd say that **if**, after thorough research, you still couldn't find it, post your code and a specific question. But even non-thorough research will find how to sort an array based on information derived from its entries. – T.J. Crowder Aug 16 '17 at 16:19
  • 2
    What has this to do with trimming? Sounds like sorting? – Jonas Wilms Aug 16 '17 at 16:19
  • Actually,there are name of months, and how to sort that, i am stucked here. – Manzer Ahmad Hashmi Aug 16 '17 at 16:21
  • 1
    items.sort((a,b) => {return new Date(a).valueOf() - new Date(b).valueOf()}); – gaetanoM Aug 16 '17 at 16:23
  • https://stackoverflow.com/questions/10123953/sort-javascript-object-array-by-date -- convert the elements of your array to date objects, then sort THEM. – Snowmonkey Aug 16 '17 at 16:24

2 Answers2

1

If you are asking about sorting the array, then you could convert the strings to Date, and then apply sort function on it.

var items = ["01-Jun-17", "03-Jun-17", "03-May-17", "05-Jun-17", "05-Jun-17", "18-May-17"];

items.sort((d1,d2) => new Date(d1) - new Date(d2) > 0);

console.log("Ascending: ",items);
console.log("Descending: ",items.reverse());
Nisarg
  • 13,121
  • 5
  • 31
  • 48
0

Here I have added both ascending and descending. You can use javascript array's function sort.

var items = ["01-Jun-17", "03-Jun-17", "03-May-17", "05-Jun-17", "05-Jun-17", "18-May-17"];

var items1 =jQuery.makeArray(items).sort(function(a, b) {
    return new Date(a) < new Date(b);
});

var items2 = jQuery.makeArray(items).sort(function(a, b) {
    return new Date(a) > new Date(b);
});
$("#div0").html(items);
$("#div1").html(items1);
$("#div2").html(items2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<lable>Original</lable>
<div id="div0"></div>
</br>

<lable>Asc</lable>
<div id="div1"></div>

</br>

<lable>Desc</lable>
<div id="div2"></div>
Power Star
  • 1,540
  • 2
  • 10
  • 24