Sort array of objects by single key with date value

后端 未结 19 1697
情话喂你
情话喂你 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: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' } ]
    */
    

提交回复
热议问题