Reputation: 59
Still new to this. I encountered a problem when trying to sort an array of objects with a Date type. For example: I have 3 cars with: (Name, Date of first registration(type Date)). How do I sort this array? Should I change date to string? Thanks.
function car(Make, Model, Date) {
return Make + Model + Date;
}
var date1 = '2010';
var date2 = '2003';
var date3 = '2015';
var d1 = new Date(date1);
var d2 = new Date(date2);
var d3 = new Date(date3);
var n1 = d1.getFullYear();
var n2 = d2.getFullYear();
var n3 = d3.getFullYear();
var x = car('Mercedes', ' c220 ', n1);
var y = car(' Toyota', ' Prius ', n2);
var z = car(' Audi', ' a3 ', n3);
var polje = [x, y, z];
console.log(polje);
.as-console-wrapper { top: 0 }
Upvotes: 0
Views: 100
Reputation: 386644
You could use Date#toISOString
for a sortable string with String#localeCompare
.
Then you could use this for sorting
var array = [
{ make: 'Mercedes', model: 'c220', date : new Date('2010') },
{ make: 'Toyota', model: 'Prius', date : new Date('2003') },
{ make: 'Audi', model: 'a3', date : new Date('2015') }
];
array.sort(function (a, b) {
return a.date.toISOString().localeCompare(b.date.toISOString());
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Version with
var array = [
{ make: 'Mercedes', model: 'c220', firstRegistration: 2010 },
{ make: 'Toyota', model: 'Prius', firstRegistration: 2015 },
{ make: 'Audi', model: 'a3', firstRegistration: 2015 }
];
array.sort(function (a, b) {
return b.firstRegistration - a.firstRegistration ||
a.make.localeCompare(b.make) ||
a.model.localeCompare(b.model);
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2