Sort array of objects by single key with date value

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

    For completeness here is a possible short generic implementation of sortBy:

    function sortBy(list, keyFunc) {
      return list.sort((a,b) => keyFunc(a) - keyFunc(b));
    }
    
    sortBy([{"key": 2}, {"key": 1}], o => o["key"])
    

    Note that this uses the arrays sort method that sorts in place. for a copy you can use arr.concat() or arr.slice(0) or similar method to create a copy.

提交回复
热议问题