skip to Main Content

I am trying to sort the Date column. Currently the sort is alphabetical order. Below is my code for your perusal.

JSON

[
  {
    "date": "Jun-2022"
  },
  {
    "date": "Jul-2022"
  },
  {
    "date": "Nov-2022"
  }
]
 columns = [
                {
                    Header: 'MONTH',
                    accessor: 'date',
                    // sortType: (a:any, b:any) => {
                    //     return new Date(b.values.date) - new Date(a.values.date);
                        
                    // }
                },

Error Message is: The left-hand side of an arithmetic operation must be of type ‘any’, ‘number’, ‘bigint’ or an enum type.ts(2362)

2

Answers


  1. When comparing date, always use the getTime() to have the time in number format.

    const dateTable = [{
        "date": "Jun-2022"
      },
      {
        "date": "Nov-2022"
      },
      {
        "date": "Jul-2022"
      },
    ]
    console.log(dateTable.sort((a, b) => (new Date(a.date).getTime() < new Date(b.date).getTime() ? -1 : 1)))
    Login or Signup to reply.
  2. You need to convert them into number format and invoke the sort with a callback function.

    The official docs of the sort would be a great start, please see sort

    My solution is below.

    const dateTable = [{
        "date": "Jun-2022"
      },
      {
        "date": "Nov-2022"
      },
      {
        "date": "Jul-2022"
      },
    ]
    
    const numberFormat = (date) => {
      return new Date(date.date).getTime();
    }
    
    console.log(dateTable.sort((a, b) => numberFormat(a) - numberFormat(b)));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search