Sort array of objects by single key with date value

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

    Here's a slightly modified version of @David Brainer-Bankers answer that sorts alphabetically by string, or numerically by number, and ensures that words beginning with Capital letters don't sort above words starting with a lower case letter (e.g "apple,Early" would be displayed in that order).

    function sortByKey(array, key) {
        return array.sort(function(a, b) {
            var x = a[key];
            var y = b[key];
    
            if (typeof x == "string")
            {
                x = (""+x).toLowerCase(); 
            }
            if (typeof y == "string")
            {
                y = (""+y).toLowerCase();
            }
    
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        });
    }
    

提交回复
热议问题