Home > Blockchain >  Sort an array of objects that is the second child of an array - By object date time
Sort an array of objects that is the second child of an array - By object date time

Time:04-15

How can I sort an [array of objects by date] that is the second child of an array ?

I get the following array structure:

array = [
    ["2022/04/14", [object]],
    ["2022/04/15", [object]],
    ["2022/04/20", [object, object, object]],
    ["2022/04/25", [object, object]],
    ["2022/04/30", [object]]
];

//where each object contain a date property that include time
//for exemple each object get :
{
param1:"someText"
date: Fri Apr 15 2022 18:00:00 GMT 0200
paramX:"someText"
}

For the days that include more than one object, objects are not sorted by time.

I've texted the following method, but can't get success with it

const sortedArray = array.sort((a, b) => {
      return new Date(a[1][1].date).getTime() - new Date(b[1][1].date).getTime();
    });

How can I sort object by time for each day of this array ?

Thank you for your help

CodePudding user response:

Surely there is a more elegant way to solve this problem but here is my approach.

// Here is the result of sorting the objects
const formattedArray = [];

const sortedArray = array.forEach((item, index) => {
  const sortedObjects = item[1].sort((a, b) => {
    return new Date(a.date) - new Date(b.date);
  });

  formattedArray[index] = [item[0], sortedObjects];
})

You don't need to use .getTime().

  • Related