Array Sort by time hh:mm:ss

前端 未结 3 1097
孤独总比滥情好
孤独总比滥情好 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:29

    You can try this

    function convertDateObj(hhmmss){
    	let obj = new Date();//creates a Date Object using the clients current time
    
        let [hours,minutes,seconds] = hhmmss.split(':'); 
    
        obj.setHours(+hours); // set the hours, using implicit type coercion
        obj.setMinutes(minutes); //you can pass Number or String, it doesn't really matter
        obj.setSeconds(seconds);
        return obj;
    }
    
    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"
      }
     ]; 
    
    elements.sort((a, b) => convertDateObj(a.date) - convertDateObj(b.date)); // Ascending order
    
    elements.sort((a, b) => convertDateObj(b.date) - convertDateObj(a.date)); // Descending order

提交回复
热议问题