JavaScriptのきほん(20)「取得したデータを加工しよう(3)sortとreduceで並べ替え・集計する」

スポンサーリンク
JavaScript

前回は、map()でデータを変換し、キーワード検索を加えた。
シリーズ最終回の今回は、一覧画面の定番である「並べ替え」と「集計」を作る。並べ替えにはsort()、担当者ごとの集計にはreduce()を使う。

sortとは

sort()は、配列を並べ替えるメソッドである。ただし、次の2つの点に注意しよう。

  • 元の配列そのものを書き換える(filter()やmap()とは違う)
  • 何も指定しないと、要素を文字列として比べる
const nums = [10, 9, 1];

console.log([...nums].sort());                 // [1, 10, 9](文字列の順)
console.log([...nums].sort((a, b) => a - b));  // [1, 9, 10](昇順)
console.log([...nums].sort((a, b) => b - a));  // [10, 9, 1](降順)

数値は、比較用の関数を渡して並べ替える。この関数は2つの要素aとbを受け取り、負の値ならaが先、正の値ならbが先になる。昇順はa - b、降順はb - aと覚えておこう。
文字列の並べ替えには、a.localeCompare(b)が使える。
また、元の配列を残したいときは、[...nums]のようにコピーを作ってから並べ替える。...は、前回出てきたスプレッド構文である。

reduceとは

reduce()は、配列の要素を1つずつ処理しながら、最終的に1つの値にまとめるメソッドである。合計や、グループごとの集計に使う。

const prices = [100, 200, 300];
const total = prices.reduce((sum, price) => sum + price, 0);

console.log(total); // 600

渡している関数は、「ここまでの結果(sum)」と「今回の要素(price)」を受け取り、新しい結果を返す。最後の0は、結果の初期値である。

今回の作り方

  • 並べ替え:選択欄を追加し、絞り込んだ結果をsort()で並べ替える
  • 集計:取得した全件から、担当者ID(userId)ごとの「完了件数・全件数・完了率」をreduce()で求める

担当者が複数いないと集計の意味がないので、件数の選択肢に50件と100件を加える。件数を増やすと、複数の担当者IDが現れる。

index.html(完成版)

前回のindex.htmlに、件数の選択肢、並べ替えの選択欄、集計の表示欄を追加する。
全体は次のとおりである。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>外部データを取得しよう</title>
</head>
<body>
  <h1>外部のToDoデータ</h1>
  <label>件数:
    <select id="limit-select">
      <option value="5">5件</option>
      <option value="10">10件</option>
      <option value="20">20件</option>
      <option value="50">50件</option>
      <option value="100">100件</option>
    </select>
  </label>
  <label>状態:
    <select id="status-select">
      <option value="all">すべて</option>
      <option value="done">完了</option>
      <option value="undone">未完了</option>
    </select>
  </label>
  <label>並べ替え:
    <select id="sort-select">
      <option value="default">取得順</option>
      <option value="id-desc">ID降順</option>
      <option value="title">タイトル順</option>
    </select>
  </label>
  <label>検索:
    <input type="text" id="search-input" placeholder="タイトルで検索">
  </label>
  <button id="reload-button">再読み込み</button>
  <p id="message"></p>

  <h2>担当者別の集計</h2>
  <ul id="summary-list"></ul>

  <h2>タスク一覧</h2>
  <ul id="todo-list"></ul>
  <script src="script.js"></script>
</body>
</html>

script.js(完成版)

script.jsを、次の内容に置き換えよう。

const BASE_URL = 'https://jsonplaceholder.typicode.com/todos';
const list = document.getElementById('todo-list');
const summaryList = document.getElementById('summary-list');
const message = document.getElementById('message');
const select = document.getElementById('limit-select');
const statusSelect = document.getElementById('status-select');
const sortSelect = document.getElementById('sort-select');
const searchInput = document.getElementById('search-input');
const button = document.getElementById('reload-button');

// 取得したデータを保存しておく配列(データがないときは null)
let allTodos = null;

// 1件のタスクを、表示用の<li>要素に変換する
function createTodoItem(todo) {
  const li = document.createElement('li');
  li.textContent = (todo.completed ? '✅ ' : '⬜ ') + todo.title;
  return li;
}

// 指定された順序で並べ替える(渡された配列そのものを書き換える)
function sortTodos(todos, order) {
  if (order === 'id-desc') {
    return todos.sort((a, b) => b.id - a.id);
  }
  if (order === 'title') {
    return todos.sort((a, b) => a.title.localeCompare(b.title));
  }
  return todos;
}

// 保存したデータを絞り込み・並べ替えて、画面に表示する
function renderTodos() {
  if (allTodos === null) {
    return;
  }

  const status = statusSelect.value;
  const keyword = searchInput.value.trim().toLowerCase();

  const filteredTodos = allTodos
    .filter((todo) => {
      if (status === 'done') {
        return todo.completed;
      }
      if (status === 'undone') {
        return !todo.completed;
      }
      return true;
    })
    .filter((todo) => todo.title.toLowerCase().includes(keyword));

  const visibleTodos = sortTodos(filteredTodos, sortSelect.value);
  list.replaceChildren(...visibleTodos.map(createTodoItem));

  if (visibleTodos.length === 0) {
    message.textContent = '該当するタスクはありません';
  } else {
    message.textContent = `${visibleTodos.length}件表示(全${allTodos.length}件)`;
  }
}

// 取得した全件を、担当者ごとに集計して表示する
function renderSummary() {
  const counts = allTodos.reduce((result, todo) => {
    if (!result[todo.userId]) {
      result[todo.userId] = { total: 0, done: 0 };
    }
    result[todo.userId].total += 1;
    if (todo.completed) {
      result[todo.userId].done += 1;
    }
    return result;
  }, {});

  const items = Object.keys(counts).map((userId) => {
    const count = counts[userId];
    const rate = Math.round((count.done / count.total) * 100);
    const li = document.createElement('li');
    li.textContent = `担当者${userId}:完了${count.done}件 / 全${count.total}件(${rate}%)`;
    return li;
  });
  summaryList.replaceChildren(...items);
}

async function loadTodos() {
  allTodos = null;
  message.textContent = '読み込み中...';
  list.innerHTML = '';
  summaryList.innerHTML = '';
  button.disabled = true;
  select.disabled = true;

  try {
    const response = await fetch(`${BASE_URL}?_limit=${select.value}`);
    if (!response.ok) {
      throw new Error(`HTTPエラー:${response.status}`);
    }
    allTodos = await response.json();
    renderTodos();
    renderSummary();
  } catch (error) {
    message.textContent = `取得に失敗した(${error.message})`;
  } finally {
    button.disabled = false;
    select.disabled = false;
  }
}

select.addEventListener('change', loadTodos);
statusSelect.addEventListener('change', renderTodos);
sortSelect.addEventListener('change', renderTodos);
searchInput.addEventListener('input', renderTodos);
button.addEventListener('click', loadTodos);
loadTodos();

コードの解説

並べ替えは、sortTodos()にまとめた。選ばれた順序に応じて、ID降順ならb.id - a.id、タイトル順ならlocaleCompare()で比べている。「取得順」のときは何もしない。
sort()は渡された配列を書き換えるが、ここで渡しているのは、filter()が作った新しい配列である。このため、保存してあるallTodosの並びは変わらず、「取得順」に戻せば、元の順序で表示される。もしallTodosに直接sort()を使うと、取得順が失われてしまう。

集計は、renderSummary()で行う。reduce()の初期値は空のオブジェクト{}で、1件ずつ処理しながら、担当者IDをキーにして「全件数total」と「完了件数done」を数えていく。まだそのIDの集計がなければ、先に{ total: 0, done: 0 }を作ってから加算している。
集計後のcountsは、{ 1: { total: 20, done: 11 }, 2: …}のような形になる。Object.keys(counts)でIDの一覧を取り出し、map()で<li>に変換して表示した。完了率は、Math.round()で整数に丸めている。

集計の表示は、全件が対象なので、データを取得したときに1回だけ行っている。状態や検索を変えても、集計は変わらない。

動作確認とまとめ

ブラウザで開き、件数を100件にしてみよう。
担当者別の集計が複数行で表示される。

続けて、並べ替えを「ID降順」「タイトル順」と切り替え、「取得順」に戻すと、元の順序に戻ることを確かめよう。

今回のポイントは次のとおりである。

  • sort()は元の配列を書き換える。元を残したいときは[...配列]でコピーする
  • 数値の並べ替えには、a - b(昇順)とb - a(降順)の比較関数が必要である
  • reduce()は、配列を1つの値(合計や、グループ別の集計)にまとめる
  • 集計の結果は、完了率のように、画面に出す形に加工して表示する

3回で扱った配列のメソッドは、次のように使い分ける。

メソッド役割戻り値元の配列
forEach()各要素に処理を実行するなし変えない
filter()条件に合う要素だけ残す新しい配列(数が減る)変えない
map()各要素を変換する新しい配列(数は同じ)変えない
sort()並べ替える並べ替えた配列自身書き換える
reduce()1つの値にまとめるまとめた値変えない

絞り込み、検索、並べ替え、集計は、どの一覧画面でも必要になる機能である。
次のステップとして、これまでに作ったToDoリストに、今回の機能を組み込んでみてほしい。

コメント

タイトルとURLをコピーしました