Home > Net >  Sorting the array of objects by key name using date-fns library in javascript
Sorting the array of objects by key name using date-fns library in javascript

Time:12-22

Here array containing the name along with the updatedTimeStamp propery. I want to sort the array based on the updatedTimeStamp property.

So I am hereby using date-fns library and I want to use this library only , I can do without this library but that's my requirement to use this library.

I can able to do sort based on the updatedTimeStamp but its not return the name how can I return the name property along with updatedTimeStamp.

import { compareDesc } from "date-fns";

let arr = [
  {
    name:"abc",
    updatedTimeStamp: "2021-12-06 14:09:00.304464"
  },
  {
   name:"xyz",
    updatedTimeStamp: "2021-12-14 13:41:58.708262"
  },
  {
    name:"thomas",
    updatedTimeStamp: "2021-12-06 15:39:09.365793"
  },
  {
    name:"Robin",
    updatedTimeStamp: "2021-12-14 09:15:42.141081"
  },
  {
    name:"Jobin",
    updatedTimeStamp: "2021-12-14 12:50:29.723421"
  },
  {
    name:"Tobin",
    
  }
];
const objArr = arr.map(i => i.updatedTimeStamp).sort(compareDesc)

CodePudding user response:

I can do without this library but that's my requirement to use this library.

Why? The date format you have can be sorted with a normal built-in sort

let arr = [
  {
    name:"abc",
    updatedTimeStamp: "2021-12-06 14:09:00.304464"
  },
  {
   name:"xyz",
    updatedTimeStamp: "2021-12-14 13:41:58.708262"
  },
  {
    name:"thomas",
    updatedTimeStamp: "2021-12-06 15:39:09.365793"
  },
  {
    name:"Robin",
    updatedTimeStamp: "2021-12-14 09:15:42.141081"
  },
  {
    name:"Jobin",
    updatedTimeStamp: "2021-12-14 12:50:29.723421"
  },
  {
    name:"Tobin",
    
  }
];
const objArr = arr.slice(0).sort((a,b) => {
 if (a.updatedTimeStamp > b.updatedTimeStamp) return 1
 if (a.updatedTimeStamp < b.updatedTimeStamp) return -1
 return 0
 })
console.log(objArr)

CodePudding user response:

I would do it like this instead. You can pas your own function which returns the comparsefunc instead

import {
  compareDesc
} from "date-fns";

let arr = [{
    name: "abc",
    updatedTimeStamp: "2021-12-06 14:09:00.304464"
  },
  {
    name: "xyz",
    updatedTimeStamp: "2021-12-14 13:41:58.708262"
  },
  {
    name: "thomas",
    updatedTimeStamp: "2021-12-06 15:39:09.365793"
  },
  {
    name: "Robin",
    updatedTimeStamp: "2021-12-14 09:15:42.141081"
  },
  {
    name: "Jobin",
    updatedTimeStamp: "2021-12-14 12:50:29.723421"
  }
];
const objArr = arr.sort((a, b) => compareDesc(a.updatedTimeStamp, b.updatedTimeStamp))

  • Related