0

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 }

2

1 Answer 1

2

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

  • firstRegistration, desc,
  • make, asc,
  • model, asc

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; }

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot! add up question: how do i make the date to show only the year? just for better looks of the output :)
you could use Date#getYear.
You can remove all date processing and get the same result. The date field should be yearOfManufacture and be a number, like 2010. But hey, it "works". ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.