Sort array of objects by single key with date value

后端 未结 19 1381
情话喂你
情话喂你 2020-11-22 10:56

I have an array of objects with several key value pairs, and I need to sort them based on \'updated_at\':

[
    {
        \"updated_at\" : \"2012-01-01T06:25         


        
19条回答
  •  失恋的感觉
    2020-11-22 11:35

    As for today, answers of @knowbody (https://stackoverflow.com/a/42418963/6778546) and @Rocket Hazmat (https://stackoverflow.com/a/8837511/6778546) can be combined to provide for ES2015 support and correct date handling:

    arr.sort((a, b) => {
       const dateA = new Date(a.updated_at);
       const dateB = new Date(b.updated_at);
       return dateA - dateB;
    });
    

提交回复
热议问题