javascriptmomentjslodash

sort array in a date string property, using lodash or moment() or simple javascript


this is my test array:

let testArray = [{'Datum':'13/05/2024','ID':1},
{'Datum':'18/05/2013','ID':2},{'Datum':'01/05/2018','ID':3},
{'Datum':'31/05/2024','ID':4},{'Datum':'31/05/2024','ID':5}]

trying to order by Datum property ascending/descending order but it is not happening here is my logic:

_.orderBy(testArray, ['Datum'], ['asc']); //not working

using moment() js

 _.orderBy(testArray, (o) => {
            return moment(o.Datum).format('DD/MM/YYYY') //not happening either
          }, ['asc']);

i tried _.sortby and sort..but array its not arranging correctly, any hints? thanks


Solution

  • Your code wasn't working because you tried to format the date instead of actually telling Moment.js what format the date is. Instead of using moment(o.Datum).format("DD/MM/YYYY"), you should use moment(o.Datum, "DD/MM/YYYY"). That said below are the 2 solutions:

    // Test array  
    const testArray = [
      { Datum: "13/05/2024", ID: 1 },
      { Datum: "18/05/2013", ID: 2 },
      { Datum: "01/05/2018", ID: 3 },
      { Datum: "31/05/2024", ID: 4 },
      { Datum: "31/05/2024", ID: 5 },
    ];
    

    Vanilla js with moment

    This works by first mapping an array of items (item.Datum) into Moment.js date objects using the format DD/MM/YYYY. Then, it sorts these date objects in both ascending and descending order.

    const mappedTestArray = testArray.map((item) =>
      moment(item.Datum, "DD/MM/YYYY")
    );
    
    // ASC ORDER
    console.log(mappedTestArray.sort((a, b) => a.diff(b)));
    
    // DESC ORDER
    console.log(mappedTestArray.sort((a, b) => b.diff(a)));
    

    The most important thing here is sorting part and how Array.sort() works . Here's the basic working :

    And using moment(...).diff(...) returns the difference i.e number so, a.diff(b) returns a negative number if a is before b, zero if a is the same as b, and a positive number if a is after b.

    With lodash & moment ( yours corrected one )

    This approach uses _.orderBy function for sorting. The sorting key is a parsed date, which is created by passing the Datum value through Moment.js with the format DD/MM/YYYY. By specifying ["desc"], the array is sorted in descending order.

    const sortedArray = _.orderBy(
      testArray,
      (o) => {
        return moment(o.Datum, "DD/MM/YYY"); // the real bug fix ! 
      },
      ["desc"]
    );
    
    console.log(sortedArray);