1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript 】配列内に定義している日付を昇順に並べ替えたい

Posted at

はじめに

配列内に定義している日付を降順に並べ替える方法について調べたことをまとめます。

問題

配列を登録データの降順(新しい日付から古い日付)に並べ替えたい

解決方法

sort()関数を使う

比較関数 (a, b) => 戻り値 の戻り値で順序が決まります。

  • 戻り値が負の数: aを前に配置
  • 戻り値が正の数: bを前に配置
  • 戻り値が0: 順序を変更しない

で並び替えを行います。

type all_data = {
  title: string;
  key: string;
  url: string;
  image_url: string;
  description: string | undefined;
  updated_at: string;
};

const all_data: all_data[] = [];
// 値の設定は省略

// 日付順(降順)に並び替え
  all_data.sort(
     (a, b) =>
      new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()
  );
  • 降順(新しい日付から古い日付)の場合:b-a > 0を計算
  • 昇順(古い日付から新しい日付)の場合:a-b > 0を計算

bの日付が新しい場合、b-a > 0となり、bの要素が前に配置されます。

all_data.sort()で行うと、文字列での比較になってしまいます。

なぜgetTime()を使うのか

dateでオブジェクトを作成し、引き算を行った場合、暗黙的な型変換が行われます。
getTime()を明示的に指定することで、ミリ秒の数値をnumber型で返却し、引き算を行ってくれます。
number型を明示的に指定することができます。

  // Date型の計算、暗黙的に型変換してくれている
  all_data.sort(
    (a, b) =>
      new Date(b.updated_at) - new Date(a.updated_at)
  );

    // number型に変換
    all_data.sort(
     (a, b) =>
      new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()
  );

おわりに

日付のソートは、型変換を意識しないといけないと思える出来事でした。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?