0
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?

日付によるソート

Posted at
interface Item {
  id: number;
  date: string; // 日付は "YYYY/MM/DD" または空文字列 ""
}

const items: Item[] = [
  { id: 1, date: "2024/11/25" },
  { id: 2, date: "2023/03/15" },
  { id: 3, date: "" }, // 空文字列データ
  { id: 4, date: "" },
  { id: 5, date: "" },
  { id: 6, date: "2024/01/10" },
  { id: 8, date: "2024/01/12" },
  { id: 9, date: "2023/01/10" },
  { id: 10, date: "2025/01/10" },
  { id: 11, date: "" }  // 追加の空文字列データ
];

// ソート処理
items.sort((a, b) => {
  // 両方がブランクの場合は順序を維持
  if (a.date === "" && b.date === "") return 0;

  // a がブランクの場合は後ろに移動
  if (a.date === "") return 1;

  // b がブランクの場合は後ろに移動
  if (b.date === "") return -1;

  // 両方ともブランクでない場合、日付を比較(降順)
  const dateA = new Date(a.date);
  const dateB = new Date(b.date);
  return dateB.getTime() - dateA.getTime();
});

console.log(items);

0
0
1

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
0
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?