Sort array of objects by single key with date value

后端 未结 19 1382
情话喂你
情话喂你 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:58

    Just another, more mathematical, way of doing the same thing but shorter:

    arr.sort(function(a, b){
        var diff = new Date(a.updated_at) - new Date(b.updated_at);
        return diff/(Math.abs(diff)||1);
    });
    

    or in the slick lambda arrow style:

    arr.sort((a, b) => {
        var diff = new Date(a.updated_at) - new Date(b.updated_at);
        return diff/(Math.abs(diff)||1);
    });
    

    This method can be done with any numeric input

提交回复
热议问题