Open In App

How to Sort a Multidimensional Array in JavaScript by Date ?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Sorting a Multidimensional Array by date consists of ordering the inner arrays based on the date values. This needs to be done by converting the date representation into the proper comparable formats and then applying the sorting function to sort the array in ascending or descending order.

Below are the possible approaches:

Using localeCompare() method

The localeCompare() method in JavaScript is mainly used for sorting by comparing the string representations in a locale-sensitive manner and ensuring the correct order.

Syntax:

string1.localeCompare(string2, locales, options);

Example: The below code uses the localeCompare() method to sort a multidimensional array in JavaScript by date.

Javascript




let arr = [
    ["GeeksforGeeks", "2023-01-15"],
    ["JavaScript", "2022-05-20"],
    ["Array", "2022-03-10"]
];
arr.sort((a, b) => a[1].localeCompare(b[1]));
console.log(arr);


Output

[
  [ 'Array', '2022-03-10' ],
  [ 'JavaScript', '2022-05-20' ],
  [ 'GeeksforGeeks', '2023-01-15' ]
]

Using new Date().getTime() method

The getTime() method of new Date() converts the data strings into the multidimensional array and performs the numerical comparison by ensuring the correct sorting order is based on the dates.

Syntax:

dateObject.getTime();

Example: The below code uses the new Date().getTime() method to sort a multidimensional array in JavaScript by date.

Javascript




let arr = [
    ["GeeksforGeeks", "2023-01-15"],
    ["JavaScript", "2022-05-20"],
    ["Array", "2022-03-10"]
];
arr.sort((a, b) =>
    new Date(a[1]).getTime() - new Date(b[1]).getTime());
console.log(arr);


Output

[
  [ 'Array', '2022-03-10' ],
  [ 'JavaScript', '2022-05-20' ],
  [ 'GeeksforGeeks', '2023-01-15' ]
]

Using Date.parse() method

The Date.parse() method mainly converts the date string into the timestamps. Then it performs the numeric comparison to sort a multidimensional array based on the dates, by creating a sorted array in ascending order of dates.

Syntax:

Date.parse(dateString)

Example: The below code uses the Date.parse() method to sort a multidimensional array in JavaScript by date.

Javascript




let arr = [
    ["GeeksforGeeks", "2023-01-15"],
    ["JavaScript", "2022-05-20"],
    ["Array", "2022-03-10"]
];
arr.sort((a, b) =>
    Date.parse(a[1]) - Date.parse(b[1]));
console.log(arr);


Output

[
  [ 'Array', '2022-03-10' ],
  [ 'JavaScript', '2022-05-20' ],
  [ 'GeeksforGeeks', '2023-01-15' ]
]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads