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



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)

Answer

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"
  }
];
// careful since this modifies the original array 
arr.sort((a, b) => compareDesc(a.updatedTimeStamp, b.updatedTimeStamp))

// to not mutate the original you can do this
const objArr = [...arr].sort((a, b) => compareDesc(a.updatedTimeStamp, b.updatedTimeStamp))


Source: stackoverflow