メインコンテンツへスキップ
見出し画像

はじめてのJavaScript #35|データを整理しよう ── 並び替えと検索機能を追加する

    今回のゴール

    ToDoリストに並び替えと検索機能を追加して、データを自在に整理できるようになる。

    第7章の総まとめ!

    LocalStorage編ではここまで以下を学んできました。

    画像

    今回は #33 で作ったToDoリストをベースに並び替えと検索機能を追加します。データが増えてきたときに「探せる・整理できる」ことはアプリの使いやすさを大きく左右します。

    並び替えの考え方

    JavaScriptの配列には sort() というメソッドがあります。

    js

    const nums = [3, 1, 4, 1, 5];
    nums.sort(function(a, b) { return a - b; });
    console.log(nums); // [1, 1, 3, 4, 5]

    sort() に比較関数を渡すことで、並び順を自由にコントロールできます。

    画像

    今回は3種類の並び替えを実装します。

    js

    // 追加順(デフォルト)
    todos.sort(function(a, b) { return a.id - b.id; });
    
    // 未完了を先に
    todos.sort(function(a, b) { return a.completed - b.completed; });
    
    // 完了済みを先に
    todos.sort(function(a, b) { return b.completed - a.completed; });

    検索の考え方

    検索は filter() と includes() を組み合わせます。

    js

    const keyword = "買い物";
    const filtered = todos.filter(function(todo) {
      return todo.text.includes(keyword);
    });

    includes() は文字列の中に指定した文字が含まれるかどうかを true/false で返します。大文字・小文字を区別しないようにするには両方を小文字に変換してから比較します。

    js

    todo.text.toLowerCase().includes(keyword.toLowerCase())

    実際に書いてみよう

    画像

    index.html

    html

    <!DOCTYPE html>
    <html lang="ja">
      <head>
        <meta charset="UTF-8">
        <title>ToDoリスト(並び替え・検索)</title>
        <style>
          body {
            font-family: sans-serif;
            max-width: 520px;
            margin: 40px auto;
            padding: 0 20px;
          }
          .input-area {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
          }
          .input-area input {
            flex: 1;
            padding: 8px 12px;
            font-size: 15px;
            border: 1px solid #ccc;
            border-radius: 6px;
          }
          .input-area button {
            padding: 8px 16px;
            font-size: 15px;
            background: royalblue;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
          }
          .toolbar {
            display: flex;
            gap: 8px;
            margin-bottom: 14px;
            flex-wrap: wrap;
          }
          .toolbar input {
            flex: 1;
            padding: 7px 12px;
            font-size: 14px;
            border: 1px solid #ccc;
            border-radius: 6px;
            min-width: 140px;
          }
          .toolbar select {
            padding: 7px 12px;
            font-size: 14px;
            border: 1px solid #ccc;
            border-radius: 6px;
            background: white;
            cursor: pointer;
          }
          .todo-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 12px;
            margin: 6px 0;
            background: #f9f8f5;
            border-radius: 8px;
            border: 0.5px solid #ddd;
          }
          .todo-item.completed .todo-text {
            text-decoration: line-through;
            color: #aaa;
          }
          .todo-text {
            flex: 1;
            font-size: 15px;
          }
          .todo-text mark {
            background: #fff176;
            border-radius: 2px;
          }
          .btn-delete {
            background: none;
            border: none;
            color: #e74c3c;
            font-size: 18px;
            cursor: pointer;
          }
          .summary {
            font-size: 13px;
            color: #888;
            margin-top: 12px;
          }
          .btn-clear {
            margin-top: 10px;
            padding: 6px 14px;
            font-size: 13px;
            background: #e74c3c;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
          }
          .no-result {
            color: #aaa;
            font-size: 14px;
            padding: 10px 0;
          }
        </style>
      </head>
      <body>
        <h1>ToDoリスト</h1>
    
        <div class="input-area">
          <input id="todoInput" type="text" placeholder="タスクを入力してください">
          <button id="btnAdd">追加</button>
        </div>
    
        <div class="toolbar">
          <input id="searchInput" type="text" placeholder="🔍 キーワードで検索">
          <select id="sortSelect">
            <option value="default">追加順</option>
            <option value="incomplete">未完了を先に</option>
            <option value="completed">完了済みを先に</option>
            <option value="name">名前順</option>
          </select>
        </div>
    
        <ul id="todoList"></ul>
    
        <p class="summary" id="summary"></p>
        <button class="btn-clear" id="btnClear">完了済みをまとめて削除</button>
    
        <script src="script.js"></script>
      </body>
    </html>

    script.js

    js

    const todoInput   = document.getElementById("todoInput");
    const btnAdd      = document.getElementById("btnAdd");
    const searchInput = document.getElementById("searchInput");
    const sortSelect  = document.getElementById("sortSelect");
    const todoList    = document.getElementById("todoList");
    const summary     = document.getElementById("summary");
    const btnClear    = document.getElementById("btnClear");
    
    // ============================================
    // LocalStorage の読み書き
    // ============================================
    function loadTodos() {
      const saved = localStorage.getItem("todos");
      return saved ? JSON.parse(saved) : [];
    }
    
    function saveTodos(todos) {
      localStorage.setItem("todos", JSON.stringify(todos));
    }
    
    // ============================================
    // 並び替え
    // ============================================
    function sortTodos(todos, order) {
      const sorted = [...todos]; // 元の配列を変えないようにコピー
    
      if (order === "incomplete") {
        sorted.sort(function(a, b) { return a.completed - b.completed; });
      } else if (order === "completed") {
        sorted.sort(function(a, b) { return b.completed - a.completed; });
      } else if (order === "name") {
        sorted.sort(function(a, b) { return a.text.localeCompare(b.text, "ja"); });
      } else {
        sorted.sort(function(a, b) { return a.id - b.id; });
      }
    
      return sorted;
    }
    
    // ============================================
    // 検索(キーワードのハイライト付き)
    // ============================================
    function highlightText(text, keyword) {
      if (!keyword) return text;
      const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
      const regex   = new RegExp("(" + escaped + ")", "gi");
      return text.replace(regex, "<mark>$1</mark>");
    }
    
    // ============================================
    // サマリーを更新する
    // ============================================
    function updateSummary(todos, filtered) {
      const total     = todos.length;
      const completed = todos.filter(function(t) { return t.completed; }).length;
      const shown     = filtered.length;
      let text        = "全" + total + "件中 " + completed + "件完了";
      if (shown !== total) text += "(" + shown + "件表示中)";
      summary.textContent = text;
    }
    
    // ============================================
    // リストを描画する
    // ============================================
    function renderTodos() {
      const todos    = loadTodos();
      const keyword  = searchInput.value.trim();
      const order    = sortSelect.value;
    
      // 検索で絞り込む
      const filtered = todos.filter(function(todo) {
        return todo.text.toLowerCase().includes(keyword.toLowerCase());
      });
    
      // 並び替える
      const sorted = sortTodos(filtered, order);
    
      todoList.innerHTML = "";
    
      if (sorted.length === 0) {
        const li       = document.createElement("li");
        li.className   = "no-result";
        li.textContent = keyword
          ? "「" + keyword + "」に一致するタスクはありません。"
          : "タスクがありません。追加してみましょう!";
        todoList.appendChild(li);
        updateSummary(todos, filtered);
        return;
      }
    
      sorted.forEach(function(todo) {
        const li       = document.createElement("li");
        li.className   = "todo-item" + (todo.completed ? " completed" : "");
    
        // チェックボックス
        const checkbox   = document.createElement("input");
        checkbox.type    = "checkbox";
        checkbox.checked = todo.completed;
        checkbox.addEventListener("change", function() {
          toggleTodo(todo.id);
        });
    
        // タスクのテキスト(キーワードをハイライト)
        const span     = document.createElement("span");
        span.className = "todo-text";
        span.innerHTML = highlightText(todo.text, keyword);
    
        // 削除ボタン
        const btnDelete       = document.createElement("button");
        btnDelete.className   = "btn-delete";
        btnDelete.textContent = "✕";
        btnDelete.addEventListener("click", function() {
          deleteTodo(todo.id);
        });
    
        li.appendChild(checkbox);
        li.appendChild(span);
        li.appendChild(btnDelete);
        todoList.appendChild(li);
      });
    
      updateSummary(todos, filtered);
    }
    
    // ============================================
    // タスクを追加する
    // ============================================
    function addTodo() {
      const text = todoInput.value.trim();
      if (!text) {
        todoInput.focus();
        return;
      }
    
      const todos   = loadTodos();
      const newTodo = {
        id:        Date.now(),
        text:      text,
        completed: false
      };
    
      todos.push(newTodo);
      saveTodos(todos);
      todoInput.value = "";
      renderTodos();
    }
    
    // ============================================
    // 完了・未完了を切り替える
    // ============================================
    function toggleTodo(id) {
      const todos = loadTodos();
      const todo  = todos.find(function(t) { return t.id === id; });
      if (todo) todo.completed = !todo.completed;
      saveTodos(todos);
      renderTodos();
    }
    
    // ============================================
    // タスクを1件削除する
    // ============================================
    function deleteTodo(id) {
      const todos    = loadTodos();
      const filtered = todos.filter(function(t) { return t.id !== id; });
      saveTodos(filtered);
      renderTodos();
    }
    
    // ============================================
    // 完了済みをまとめて削除する
    // ============================================
    btnClear.addEventListener("click", function() {
      const todos      = loadTodos();
      const incomplete = todos.filter(function(t) { return !t.completed; });
      if (todos.length === incomplete.length) {
        alert("完了済みのタスクはありません。");
        return;
      }
      if (!confirm("完了済みのタスクをすべて削除しますか?")) return;
      saveTodos(incomplete);
      renderTodos();
    });
    
    // ============================================
    // イベント
    // ============================================
    btnAdd.addEventListener("click", function() { addTodo(); });
    todoInput.addEventListener("keydown", function(e) {
      if (e.key === "Enter") addTodo();
    });
    searchInput.addEventListener("input", function() { renderTodos(); });
    sortSelect.addEventListener("change", function() { renderTodos(); });
    
    // 初期描画
    renderTodos();

    コードのポイント解説

    スプレッド構文で配列をコピーする

    sort() は元の配列を直接書き換えてしまいます。LocalStorageのデータを勝手に並び替えないよう、コピーしてから並び替えています。

    js

    const sorted = [...todos]; // スプレッド構文でコピー

    [...todos] はスプレッド構文といい、配列の全要素を展開した新しい配列を作ります。次の第8章でくわしく学びます。

    localeCompare() で日本語の名前順に並べる

    js

    a.text.localeCompare(b.text, "ja")

    localeCompare() は文字列を言語のルールに従って比較します。第2引数に "ja" を指定することで日本語の五十音順に対応した並び替えができます。

    キーワードをハイライト表示する

    検索キーワードに一致した部分を <mark> タグで囲んで黄色くハイライト表示しています。正規表現の特殊文字をエスケープしてから使うのがポイントです。

    js

    const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    const regex   = new RegExp("(" + escaped + ")", "gi");
    return text.replace(regex, "<mark>$1</mark>");

    まとめ

    • sort() に比較関数を渡すことで自由な順番に並び替えられる

    • filter() と includes() を組み合わせてキーワード検索が実装できる

    • sort() は元の配列を書き換えるのでスプレッド構文でコピーしてから使う

    次回予告

    LocalStorage編はここで完結です。
    次回からは第8章モダンなJavaScript編に突入しますよ~(^^)/。アロー関数をはじめとした現代の書き方を身につけましょう。

    → #36|アロー関数って何? ── function をすっきり書き直す


     
     
    高知県で小さなプログラミングスクールと学習塾、職業訓練校などを運営。 地方で貴重な学びの選択肢を提案・提供することに使命感を持ちつつ、既存の教育論や学びの空間そのものに対する問題を素直に考えながら、日々の学びが楽しくなる生き方や考え方を模索しています。 ギフテッドで猫好き。

    あなたへのおすすめ