How to sort date array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array that contains some dates like this −

const arr = [
   [ '02/13/2015', 0.096 ],
   [ '11/15/2013', 0.189 ],
   [ '05/15/2014', 0.11 ],
   [ '12/13/2013', 0.1285 ],
   [ '01/15/2013', 0.12 ],
   [ '01/15/2014', 0.11 ],
   [ '02/14/2014', 0.11 ],
   [ '03/14/2014', 0.11 ],
   [ '01/15/2015', 0.096 ],
   [ '07/15/2015', 0.096 ],
   [ '04/15/2013', 0.12 ],
   [ '04/15/2014', 0.11 ],
   [ '05/15/2013', 0.12 ],
   [ '06/14/2013', 0.12 ],
   [ '06/16/2014', 0.11 ],
   [ '07/15/2013', 0.12 ],
   [ '07/15/2014', 0.11 ],
   [ '03/16/2015', 0.096 ]
];

We are required to write a JavaScript function that takes in one such array and sorts the array in ascending order according to the dates in each array.

Example

Following is the code −

const arr = [
   [ '02/13/2015', 0.096 ],
   [ '11/15/2013', 0.189 ],
   [ '05/15/2014', 0.11 ],
   [ '12/13/2013', 0.1285 ],
   [ '01/15/2013', 0.12 ],
   [ '01/15/2014', 0.11 ],
   [ '02/14/2014', 0.11 ],
   [ '03/14/2014', 0.11 ],
   [ '01/15/2015', 0.096 ],
   [ '07/15/2015', 0.096 ],
   [ '04/15/2013', 0.12 ],
   [ '04/15/2014', 0.11 ],
   [ '05/15/2013', 0.12 ],
   [ '06/14/2013', 0.12 ],
   [ '06/16/2014', 0.11 ],
   [ '07/15/2013', 0.12 ],
   [ '07/15/2014', 0.11 ],
   [ '03/16/2015', 0.096 ]
];
const sortByDate = arr => {
   const sorter = (a, b) => {
      return new Date(a[0]) - new Date(b[0]);
   };
   arr.sort(sorter);
};
sortByDate(arr);
console.log(arr);

Output

This will produce the following output on console −

[
   [ '01/15/2013', 0.12 ],
   [ '04/15/2013', 0.12 ],
   [ '05/15/2013', 0.12 ],
   [ '06/14/2013', 0.12 ],
   [ '07/15/2013', 0.12 ],
   [ '11/15/2013', 0.189 ],
   [ '12/13/2013', 0.1285 ],
   [ '01/15/2014', 0.11 ],
   [ '02/14/2014', 0.11 ],
   [ '03/14/2014', 0.11 ],
   [ '04/15/2014', 0.11 ],
   [ '05/15/2014', 0.11 ],
   [ '06/16/2014', 0.11 ],
   [ '07/15/2014', 0.11 ],
   [ '01/15/2015', 0.096 ],
   [ '02/13/2015', 0.096 ],
   [ '03/16/2015', 0.096 ],
   [ '07/15/2015', 0.096 ]
]
raja
Published on 01-Oct-2020 11:09:15
Advertisements