如何根据时间在对象数组中排序?

时间:2019-04-08 09:29:22

标签: javascript sorting object momentjs

我有一个对象数组,例如

[{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20",
  key2: "",
  key3: ""
}]

,我希望他们根据时间进行排序。我对momentjs进行了一些研究,但没有发现有用的东西。

我面临的主要问题是如何将我转换为String格式的时间转换为某种可比较的格式进行排序。任何帮助将不胜感激。谢谢。

6 个答案:

答案 0 :(得分:3)

您一直都在同一日期约会。然后getTime()进行比较

let arr = [{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20",
  key2: "",
  key3: ""
}]

const toTime = (t) => new Date(`December 17, 1995 ${t}`).getTime();


arr.sort((a,b) => toTime(a.time) - toTime(b.time))

console.log(arr)

答案 1 :(得分:2)

您可以获取给定时间的分钟数,然后按此值排序。

const getMinutes = s => s.split(':').reduce((h, m) => h * 60 + m);

var array = [{ time: "13:20", key2: "", key3: "" }, { time: "13:40", key2: "", key3: "" }, { time: "04:20", key2: "", key3: "" }];

array.sort((a, b) => getMinutes(a.time) - getMinutes(b.time));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:2)

如果您的时间字符串为HH:MM格式,则可以简单地对String.prototype.localeCompare()进行字典排序:

const data = [
  { time: '13:20', key2: '', key3: '' },
  { time: '13:40', key2: '', key3: '' },
  { time: '04:20', key2: '', key3: '' },
  { time: '23:03', key2: '', key3: '' }
];

const ascending = [...data].sort((a, b) => a.time.localeCompare(b.time));
const descending = [...data].sort((a, b) => b.time.localeCompare(a.time));

console.log(JSON.stringify(ascending));
console.log(JSON.stringify(descending));

如果您的时间字符串不遵循此格式,即可以指定为HHHHH:MHH:MM ...,那么您可以使用RegExp.prototype.exec()解析字符串:

const data = [
  { time: '13:20', key2: '', key3: '' },
  { time: '13:40', key2: '', key3: '' },
  { time: '04:20', key2: '', key3: '' },
  { time: ' 4:25', key2: '', key3: '' },
  { time: '23:03', key2: '', key3: '' },
  { time: '14: 3', key2: '', key3: '' },
  { time: ' 2   ', key2: '', key3: '' },
];

const hourMinutes = str => /\s*(?<hh>\d*)\s*:?\s*(?<mm>\d*)\s*/.exec(str);
const toMinutes = ({ hh = 0, mm = 0 }) => (+hh) * 60 + (+mm);
const toTime = ({ time }) => toMinutes(hourMinutes(time).groups);

const ascending = [...data].sort((a, b) => toTime(a) - toTime(b));
const descending = [...data].sort((a, b) => toTime(b) - toTime(a));

console.log(JSON.stringify(ascending));
console.log(JSON.stringify(descending));

答案 3 :(得分:2)

您可以采用以下方法对其进行排序:

逻辑

  • 创建日期对象并添加所需的时间值。
  • 根据这些日期值对其进行排序。

采用基于日期的方法的好处是它将处理所有时间价值案件。我已更新数据以具有第二个值以进行演示

   LatLng oldLocation, newLocaation;

float bearing = (float) bearingBetweenLocations(oldLocation, newLocaation);
rotateMarker(marker, bearing);

private double bearingBetweenLocations(LatLng perviousPos,LatLng newPos) {

    double PI = 3.14159;
    double lat1 = perviousPos.latitude * PI / 180;
    double long1 = perviousPos.longitude * PI / 180;
    double lat2 = newPos.latitude * PI / 180;
    double long2 = newPos.longitude * PI / 180;

    double dLon = (long2 - long1);

    double y = Math.sin(dLon) * Math.cos(lat2);
    double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
            * Math.cos(lat2) * Math.cos(dLon);

    double brng = Math.atan2(y, x);

    brng = Math.toDegrees(brng);
    brng = (brng + 360) % 360;

    return brng;
}


   .To rotate marker using above bearing angle i have used this code

 Here isMarkerRotating is a boolean value. Add isMarkerRotating = false in OnCreate 
method

private void rotateMarker(final Marker marker, final float toRotation) {
    if(!isMarkerRotating) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        final float startRotation = marker.getRotation();
        final long duration = 2000;

        final Interpolator interpolator = new LinearInterpolator();

        handler.post(new Runnable() {
            @Override
            public void run() {
                isMarkerRotating = true;

                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed / duration);

                float rot = t * toRotation + (1 - t) * startRotation;

                float bearing =  -rot > 180 ? rot / 2 : rot;

                marker.setRotation(bearing);

                if (t < 1.0) {
                    // Post again 16ms later.
                    handler.postDelayed(this, 16);
                } else {
                    isMarkerRotating = false;
                }
            }
        });
    }
}

答案 4 :(得分:1)

您可以简单地得到:之前的第一个数字部分,并进行比较以进行排序,如果第一部分相同,则考虑:之后的第二个数字部分

升序排列

var arr = [{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20",
  key2: "",
  key3: ""
}];

arr.sort(function(a, b) {
  var aSplit = a.time.split(':');
  var bSplit = b.time.split(':');
  return (aSplit[0] - bSplit[0] || aSplit[1] - bSplit[1]);
});
console.log(arr);

降序排列

var arr = [{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20",
  key2: "",
  key3: ""
}];

arr.sort(function(a, b) {
  var aSplit = a.time.split(':');
  var bSplit = b.time.split(':');
  return (bSplit[0] - aSplit[0] || bSplit[1] - aSplit[1]);
});
console.log(arr);

答案 5 :(得分:1)

您可以在传递给time的自定义回调中对每个项目的Array#sort()字段进行解析和排序,如下所示:

const input = [ { time : "13:20" , key2: "", key3: ""},{ time : "13:40" , key2: "", key3: ""},{ time : "04:20" , key2: "", key3: ""}];


const output = input.sort((a, b) => {
  
  const [aHours, aMinutes] = a.time.split(':');
  const [bHours, bMinutes] = b.time.split(':');
  
  if(aHours < bHours) {
    return -1;
  }
  else if(aHours > bHours) {
    return 1;
  }
  else {
    
    if(aMinutes < bMinutes) {
      return -1;
    }
    else if(aMinutes > bMinutes) {
      return 1;
    }
  }
  
  return 0; 
});

console.log(output);