Home > Software design >  date time sorting with nested objects in javascript
date time sorting with nested objects in javascript

Time:03-18

I have a condition where I'm stuck right now, so basically I want to sort my array with the values of its nested array. I want to sort the parent array called arr with the date-time of its nested array called notifications. I want only those objects should come first which has updated createdAt of notifications.

const arr = [ 
    {
        "name": "Two"
        "notifications": [
            {
                "name": "Notification of two (1)",
                "createdAt": "2021-03-17T10:30:03.629262Z"
            },
            {
                "name": "Notification of two (1)",
                "createdAt": "2021-03-17T10:30:03.629262Z"
            }
        ]
    },
    {
        "name": "One"
        "notifications": [
            {
                "name": "Notification of one (1)",
                "createdAt": "2022-03-17T10:30:03.629262Z"
            },
            {
                "name": "Notification of one (1)",
                "createdAt": "2022-03-17T10:30:03.629262Z"
            }
        ]
    }    
]

CodePudding user response:

Here's one way to solve the problem. It calculates the maximum date for each item's notification and then performs a descending sort on that maximum date.

const arr = [
  {
    name: "Two",
    notifications: [
      {
        name: "Notification of two (1)",
        createdAt: "2021-03-17T10:30:03.629262Z",
      },
      {
        name: "Notification of two (1)",
        createdAt: "2021-03-17T10:30:03.629262Z",
      },
    ],
  },
  {
    name: "One",
    notifications: [
      {
        name: "Notification of one (1)",
        createdAt: "2022-03-17T10:30:03.629262Z",
      },
      {
        name: "Notification of one (1)",
        createdAt: "2022-03-17T10:30:03.629262Z",
      },
    ],
  },

];

const max_date = (x) =>
  Math.max.apply(
    null,
    x.notifications.map((n) => new Date(n.createdAt))
  );

// descending sort by maximum date
arr.sort((x, y) => max_date(y) - max_date(x));
console.log(arr);

  • Related