Array Sort by time hh:mm:ss

前端 未结 3 1081
孤独总比滥情好
孤独总比滥情好 2021-01-07 15:36

I am trying to sort the time. but I am unable to sort by time (hh:mm:ss) format. so i have used moments js. my array sort by time not get sorted. how sort array by using map

3条回答
  •  独厮守ぢ
    2021-01-07 16:20

    The parsedDates map you've created is looking like:

    Map {
      [ 'id', 'date' ] => [ 1,  ],
      [ 'id', 'date' ] => [ 2,  ],
      [ 'id', 'date' ] => [ 3,  ],
      [ 'id', 'date' ] => [ 4,  ]
    }
    

    And then you try to extract from it with elements like this:

    parsedDates.get({ "id": 1, "date": "02:01:02" })
    

    This should not work, because the key in a Map is and Array instance.

    Even if you were using an array as a key:

    parsedDates.get([ 1, "02:01:02" ])
    

    this still wouldn't work, as this would be a different Object reference. I mean two arrays

    a = [ 1, "02:01:02" ]
    b = [ 1, "02:01:02" ]
    

    are stored in different places and are different Objects, even though their values are identical.

    So, you can modify your solution a bit:

    let elements =[
      {
        "id": 1,
        "date": "02:01:02"
      },
      {
        "id": 2,
        "date": "01:01:01"
      },
      {
        "id": 3,
        "date": "03:01:01"
      },
      {
        "id": 4,
        "date": "04:01:01"
      }
     ]; 
    
    let parsedDates = new Map(
          elements.map(e => [e.date, e])
          );
    
    elements = elements.map(x => x.date).sort().map(x => parsedDates.get(x))
    
    console.log(elements)
    
    // [
    //   { id: 2, date: '01:01:01' },
    //   { id: 1, date: '02:01:02' },
    //   { id: 3, date: '03:01:01' },
    //   { id: 4, date: '04:01:01' }
    // ]
    

提交回复
热议问题