0

I'm little new to programming Im having trouble understanding why my sort function wont sort by date ?

var customer_orders = [
                { 
                    order_number:  1, 
                    customer: 'Jess Learmonth',    
                    total_cost: 200,    
                    processed_date: '23/01/2016' 
                },

                { 
                    order_number: 14, 
                    customer: 'Adam Bowden',       
                    total_cost: 100,    
                    processed_date: '22/01/2015' 
                }
            ];


customer_orders.sort(function(a, b) {
    var dateA = new Date(a.processed_date), dateB = new Date(b.processed_date);
    return dateA - dateB;
});
  • 1
    `'22/01/2015'` isn’t a date format recognized by the `Date` constructor. `2015-01-22` (the ISO standard) is. – Sebastian Simon Jun 25 '18 at 18:55
  • Possible duplicate of [How to convert dd/mm/yyyy string into JavaScript Date object?](https://stackoverflow.com/questions/33299687/how-to-convert-dd-mm-yyyy-string-into-javascript-date-object) – Sebastian Simon Jun 25 '18 at 18:56

3 Answers3

0

It is not sorted, as your date format is not reconized. You can try the following:

var customer_orders = [{order_number:1,customer:'Jess Learmonth',total_cost:200,processed_date:'23/01/2016'},{order_number:14,customer:'Adam Bowden',total_cost:100,processed_date:'22/01/2015'}];

customer_orders.sort((a,b)=> a.processed_date.split('/').reverse().join('').localeCompare(b.processed_date.split('/').reverse().join('')));

console.log(customer_orders);
amrender singh
  • 7,949
  • 3
  • 22
  • 28
0

Since your date format is not the recognized one by date, you can transform it like that

var customer_orders = [{
    order_number: 1,
    customer: 'Jess Learmonth',
    total_cost: 200,
    processed_date: '23/01/2016'
  },

  {
    order_number: 14,
    customer: 'Adam Bowden',
    total_cost: 100,
    processed_date: '22/01/2015'
  }
];


function reformatDate(dateString) {
    var dateParts = dateString.split("/");
    return new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
}

customer_orders.sort(function(a, b) {
  return new Date(reformatDate(a.processed_date)) - new Date(reformatDate(b.processed_date));
});

console.log(customer_orders);
Jonathan Lafleur
  • 493
  • 5
  • 25
0

You should use momentjs for parsing date and compare them for sorting -

var customer_orders = [{
    order_number: 1,
    customer: 'Jess Learmonth',
    total_cost: 200,
    processed_date: '23/01/2016'
  },

  {
    order_number: 14,
    customer: 'Adam Bowden',
    total_cost: 100,
    processed_date: '22/01/2015'
  }
];


let ans = customer_orders.sort(function(a, b) {
  var dateA = moment(a.processed_date, "DD/MM/YYYY"),
    dateB = moment(b.processed_date, "DD/MM/YYYY");
  return dateA - dateB;
});

console.log(ans);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
Vivek
  • 1,465
  • 14
  • 29