Sort array of objects by single key with date value

后端 未结 19 1346
情话喂你
情话喂你 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;
    });
    
    0 讨论(0)
  • 2020-11-22 11:36

    Data Imported

    [
        {
            "gameStatus": "1",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-20 11:32:04"
        },
        {
            "gameStatus": "0",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-19 18:08:24"
        },
        {
            "gameStatus": "2",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-19 18:35:40"
        },
        {
            "gameStatus": "0",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-19 10:42:53"
        },
        {
            "gameStatus": "2",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-20 10:54:09"
        },
        {
            "gameStatus": "0",
            "userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
            "created_at": "2018-12-19 18:46:22"
        },
        {
            "gameStatus": "1",
            "userId": "7118ed61-d8d9-4098-a81b-484158806d21",
            "created_at": "2018-12-20 10:50:48"
        }
    ]
    

    FOR Ascending order

    arr.sort(function(a, b){
        var keyA = new Date(a.updated_at),
            keyB = new Date(b.updated_at);
        // Compare the 2 dates
        if(keyA < keyB) return -1;
        if(keyA > keyB) return 1;
        return 0;
    });
    

    Example for Asc Order

    [
        {
            "gameStatus": "0",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-19 10:42:53"
        },
        {
            "gameStatus": "0",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-19 18:08:24"
        },
        {
            "gameStatus": "2",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-19 18:35:40"
        },
        {
            "gameStatus": "0",
            "userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
            "created_at": "2018-12-19 18:46:22"
        },
        {
            "gameStatus": "1",
            "userId": "7118ed61-d8d9-4098-a81b-484158806d21",
            "created_at": "2018-12-20 10:50:48"
        },
        {
            "gameStatus": "2",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-20 10:54:09"
        },
        {
            "gameStatus": "1",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-20 11:32:04"
        }
    ]
    

    FOR Descending order

    arr.sort(function(a, b){
        var keyA = new Date(a.updated_at),
            keyB = new Date(b.updated_at);
        // Compare the 2 dates
        if(keyA > keyB) return -1;
        if(keyA < keyB) return 1;
        return 0;
    });
    

    Example for Desc Order

    [
        {
            "gameStatus": "1",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-20 11:32:04"
        },
        {
            "gameStatus": "2",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-20 10:54:09"
        },
        {
            "gameStatus": "1",
            "userId": "7118ed61-d8d9-4098-a81b-484158806d21",
            "created_at": "2018-12-20 10:50:48"
        },
        {
            "gameStatus": "0",
            "userId": "1a2fefb0-5ae2-47eb-82ff-d1b2cc27875a",
            "created_at": "2018-12-19 18:46:22"
        },
        {
            "gameStatus": "2",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-19 18:35:40"
        },
        {
            "gameStatus": "0",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-19 18:08:24"
        },
        {
            "gameStatus": "0",
            "userId": "c02cfb18-ae66-430b-9524-67d9dd8f6a50",
            "created_at": "2018-12-19 10:42:53"
        }
    ]
    
    0 讨论(0)
  • 2020-11-22 11:39

    You can create a closure and pass it that way here is my example working

    $.get('https://data.seattle.gov/resource/3k2p-39jp.json?$limit=10&$where=within_circle(incident_location, 47.594972, -122.331518, 1609.34)', 
      function(responce) {
    
        var filter = 'event_clearance_group', //sort by key group name
        data = responce; 
    
        var compare = function (filter) {
            return function (a,b) {
                var a = a[filter],
                    b = b[filter];
    
                if (a < b) {
                    return -1;
                } else if (a > b) {
                    return 1;
                } else {
                    return 0;
                }
            };
        };
    
        filter = compare(filter); //set filter
    
        console.log(data.sort(filter));
    });
    
    0 讨论(0)
  • 2020-11-22 11:40

    You could use the Lodash utility library to solve this problem (it's quite an efficient library):

    const data = [{
        "updated_at": "2012-01-01T06:25:24Z",
        "foo": "bar"
      },
      {
        "updated_at": "2012-01-09T11:25:13Z",
        "foo": "bar"
      },
      {
        "updated_at": "2012-01-05T04:13:24Z",
        "foo": "bar"
      }
    ]
    
    const ordered = _.orderBy(
      data,
      function(item) {
        return item.updated_at;
      }
    );
    
    console.log(ordered)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

    You can find documentation here: https://lodash.com/docs/4.17.15#orderBy

    0 讨论(0)
  • 2020-11-22 11:40
    • Use Array.sort() to sort an array
    • Clone array using spread operator () to make the function pure
    • Sort by desired key (updated_at)
    • Convert date string to date object
    • Array.sort() works by subtracting two properties from current and next item if it is a number / object on which you can perform arrhythmic operations
    const input = [
      {
        updated_at: '2012-01-01T06:25:24Z',
        foo: 'bar',
      },
      {
        updated_at: '2012-01-09T11:25:13Z',
        foo: 'bar',
      },
      {
        updated_at: '2012-01-05T04:13:24Z',
        foo: 'bar',
      }
    ];
    
    const sortByUpdatedAt = (items) => [...items].sort((itemA, itemB) => new Date(itemA.updated_at) - new Date(itemB.updated_at));
    
    const output = sortByUpdatedAt(input);
    
    console.log(input);
    /*
    [ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
      { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' }, 
      { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' } ]
    */
    console.log(output)
    /*
    [ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
      { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' }, 
      { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' } ]
    */
    
    0 讨论(0)
  • 2020-11-22 11:41

    You can use Array.sort.

    Here's an example:

    var arr = [{
        "updated_at": "2012-01-01T06:25:24Z",
        "foo": "bar"
      },
      {
        "updated_at": "2012-01-09T11:25:13Z",
        "foo": "bar"
      },
      {
        "updated_at": "2012-01-05T04:13:24Z",
        "foo": "bar"
      }
    ]
    
    arr.sort(function(a, b) {
      var keyA = new Date(a.updated_at),
        keyB = new Date(b.updated_at);
      // Compare the 2 dates
      if (keyA < keyB) return -1;
      if (keyA > keyB) return 1;
      return 0;
    });
    
    console.log(arr);

    0 讨论(0)
提交回复
热议问题