したがって、オブジェクトの配列があり、次の2つのルールに従って(優先順位に従って)それらを並べ替えたいと思います。
ですから、オブジェクトを数字で並べ替えるだけでなく、時間でも並べ替えてほしいのです。たとえば、これは問題ありません。
これは、私たちが興味を持っているオブジェクトの部分の構造です。
var notSortedData = {
number: number, // it's a string
scheduled_date: scheduled_date, // the format is "YYYY-MM-DD HH:MM:SS"
}
sortedTrains.push(notSortedData);
したがって、ループnotSortedData
をsortedTrains
介してプッシュされfor
ます。それから私はこれをします、しかしそれは十分ではありません(それは私の2番目の条件を尊重しないので):
// sorts all the numbers numerically
sortedTrains.sort(function(a, b) {
return parseInt(a.number) - parseInt(b.number);
});
2番目の条件も尊重されるようにするにはどうすればよいですか?ありがとう!
あなたはこれを試すことができます:
sortedTrains.sort(function(a, b) {
// We parse the numbers
var num1 = parseInt(a.number), num2 = parseInt(b.number);
if (num1 != num2) return num1 - num2; // Return the difference IF they are not equal
var date1 = new Date(a.scheduled_date), date2 = new Date(b.scheduled_date);
// We only get here if the numbers are equal
return date1 - date2;
});
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加