日本語

React: Sorting Japanese Names by Reading and Grouping Them by Gojūon Row

​​React​CSS,Intl.Collator,JavaScript,Playwright,TypeScript

To sort a list of names in gojūon order, compare the readings (kana) with Intl.Collator('ja'), not the kanji. To split the list into rows such as the あ行 row and the か行 row, use an Intl.Collator with sensitivity: 'base' and compare the first character of each reading with the 10 characters あ, か, さ, た, な, は, ま, や, ら, わ. This also puts voiced characters, katakana, and half-width katakana in the same row. This approach is for screens where people's names are grouped under row headings and an index helps users find a name, such as an employee roster, member list, address book, or contact list.

Note

Tested on Ubuntu 24.04, Node.js 22.23.4 (ICU 78.3), React 19.3.1 (development build), TypeScript 7.0.2, esbuild 0.28.2, Playwright 1.63.0, and Chromium 153. I checked the screens by running Chromium with Playwright. I did not test Firefox, Safari, mobile browsers, or production builds. Generating readings from kanji automatically is outside the scope of this article.

Screenshot of the name list. The row buttons across the top use the first kana of each row (a, ka, sa, ta, ... wa) and an "other" button. The labels in the image are in Japanese. Rows with no names are gray. Below the buttons, names are listed under row headings, each with its reading.
The article’s component opened in Chromium. Names are sorted by reading in gojūon order and split into rows under headings. The labels in the image are in Japanese.

Sorting Names by Kanji Does Not Give Gojūon Order

I first sorted the kanji names directly with Intl.Collator('ja'). In the Node.js version I used, the result was:

text
阿部 佐藤 小林 上田 大野 渡辺 東海林

The names with readings こばやし, うえだ, and おおの come after the name with reading さとう. Chromium gave the same order. The collation order of kanji is not necessarily the order of their readings.

So I store the reading with each name and use it both for sorting and for choosing the row. The reading is data you receive with the name, for example from a furigana field in an input form.

ts
export type Person = { id: number; name: string; kana: string };

Sort by Reading with Intl.Collator('ja')

If you call sort() on readings with no arguments, the order follows character codes. Hiragana comes before katakana, and half-width katakana comes after that. In my verification environment, I sorted a list of readings that mixed hiragana, katakana, and half-width katakana, and compared the results (excerpt).

Sort method Result
sort() (character code order) Smith ぁ あべ かとう がもう こう … んじゃめな イトウ コウ ヴぃえら 佐藤 カトウ
sort(new Intl.Collator('ja').compare) Smith ぁ あべ イトウ ヴぃえら かとう カトウ がもう … こう コウ … んじゃめな 佐藤

With compare from Intl.Collator('ja'), katakana and half-width katakana sit in the same positions as hiragana. Comparing か with カ gives 0 (equal), and comparing か with が gives -1. The character without a voiced mark comes first.

Readings that start with Latin letters come before kana. Kanji come after kana. For how to use Intl.Collator, see the Intl.Collator page on MDN.

Decide the Row by Comparing with the First Character of Each Row

A reading that starts with が or ガ goes in the か行 row. Rather than write out a table for every character, I compare the first character with the 10 characters あ, か, さ, た, な, は, ま, や, ら, わ. The name's row is the last of these heads that is equal to or before the first character.

ts
// gojuon.ts
export type Person = { id: number; name: string; kana: string };

// Row headings. The first character of each row (a, ka, sa, ...) marks the boundary of the row
const HEADS = ['あ', 'か', 'さ', 'た', 'な', 'は', 'ま', 'や', 'ら', 'わ'] as const;
export const LABELS = [...HEADS.map((h) => `${h}行`), 'その他'];

// For sorting: keep differences such as voiced marks and small kana, so the order is fine-grained
const sortCollator = new Intl.Collator('ja');
// For choosing the row: ignore differences in voiced marks, small kana, and hiragana vs. katakana
const baseCollator = new Intl.Collator('ja', { sensitivity: 'base' });
const KANA = /^[\p{Script=Hiragana}\p{Script=Katakana}]/u;

export function rowOf(kana: string): string {
  const first = kana.trim().charAt(0);
  if (!KANA.test(first)) return 'その他';
  // Find the last row head that is less than or equal to first
  const i = HEADS.findLastIndex((head) => baseCollator.compare(first, head) >= 0);
  return i < 0 ? 'その他' : `${HEADS[i]}行`;
}

export type Group = { label: string; people: Person[] };

export function groupByRow(people: Person[]): Group[] {
  const sorted = people.toSorted(
    (a, b) => sortCollator.compare(a.kana, b.kana) || sortCollator.compare(a.name, b.name),
  );
  const byRow = Map.groupBy(sorted, (p) => rowOf(p.kana));
  return LABELS.flatMap((label) => {
    const list = byRow.get(label);
    return list ? [{ label, people: list }] : [];
  });
}

I create two Intl.Collator instances because they have different roles. For sorting, I want to tell か and が apart, so I use Intl.Collator('ja') with no options. For choosing the row, I set sensitivity to 'base'. In the sensitivity section of MDN's Intl.Collator() constructor page, 'base' treats only characters with different base letters as different.

When I chose the row with the default comparison (no options), a reading that starts with the small ぁ did not go into any row, because ぁ is compared as coming before あ. With 'base', readings starting with ぁ went into the あ行 row.

Checking that the first character is kana with a regular expression excludes strings that start with kanji. In the verification environment, when 佐 was compared with the 10 characters using the default comparison, it was judged to be わ or later, so it would have gone into the わ行 row. Names that start with a non-kana character go into その他.

The results of rowOf in the verification environment:

Reading Row
あべ, ぁ あ行
がもう, ガモウ, カトウ か行
ぱく は行
ヴぃえら あ行
わたなべ, をの, ん わ行
さとう (leading space) さ行
Emma, 佐藤, ー, empty string その他

A reading starting with ヴ goes into the あ行 row, and readings starting with を or ん go into the わ行 row.

groupByRow sorts the names by reading and then groups them by row with Map.groupBy (see the Map.groupBy page on MDN). Names with the same reading are sorted by name. At the end, it takes the rows out in the order of LABELS. Alphabetic names that go into その他 would come first in the sort, so this step makes その他 the last heading.

toSorted and findLastIndex were added in ES2023, and Map.groupBy in ES2024. In the verification environment, setting lib to ES2022 in TypeScript gave errors saying these three could not be found (TS2550, TS2551). Set lib in tsconfig.json to ES2024 or later.

A Component That Renders Headings and an Index

I put the grouped result into a section and a heading for each row. The index at the top links to each row. Rows with no names are not links. They are a span and are shown in gray with CSS.

tsx
// GojuonList.tsx
import { useMemo } from 'react';
import { LABELS, groupByRow, type Person } from './gojuon';

export function GojuonList({ people }: { people: Person[] }) {
  const groups = useMemo(() => groupByRow(people), [people]);
  const used = new Set(groups.map((g) => g.label));
  const idOf = (label: string) => `row-${LABELS.indexOf(label)}`;

  return (
    <div>
      <nav aria-label="行で移動">
        <ul className="index">
          {LABELS.map((label) => (
            <li key={label}>
              {used.has(label) ? (
                <a href={`#${idOf(label)}`}>{label.replace('行', '')}</a>
              ) : (
                <span aria-disabled="true">{label.replace('行', '')}</span>
              )}
            </li>
          ))}
        </ul>
      </nav>
      {groups.map((g) => (
        <section key={g.label} aria-labelledby={idOf(g.label)}>
          <h2 id={idOf(g.label)}>{g.label}</h2>
          <ul>
            {g.people.map((p) => (
              <li key={p.id}>
                {p.name}
                <span className="kana">{p.kana}</span>
              </li>
            ))}
          </ul>
        </section>
      ))}
    </div>
  );
}

The heading ids are numbered from row-0 (あ行) through row-10 (その他). I put sorting and grouping in useMemo, so they run again only when people changes.

When I passed data for 13 people and opened the page in Chromium, the headings and names appeared as follows. A person whose reading is カトウ ハル (katakana) is also listed before the hiragana がもう in the ka-row.

text
あ行:阿部 葵、上田 蓮、大野 光
か行:加藤 陽、蒲生 凛、小林 湊
さ行:佐藤 結、東海林 誠
は行:馬場 樹、林 花
や行:山田 翼
わ行:渡辺 健
その他:Emma Smith

If the Index Stays at the Top, Add scroll-margin-top to the Headings

If the list is long, you can keep the index fixed at the top of the screen with position: sticky, so you can switch rows from any scroll position. But with that alone, the heading you jump to from the index is hidden under the index.

css
nav {
  position: sticky;
  top: 0;
  background: #fff;
}
h2 {
  scroll-margin-top: 5.5rem;
}
.index span {
  color: #9aa5ab;
}

Put position: sticky on the nav, not on the ul. In the verification environment, when I put it on the ul inside a nav that held only the ul, the index also went off the screen after scrolling 400px.

I set the screen width to 390px and the height to 300px, then pressed the か button in the index and compared the results. After scrolling, the bottom edge of the index was at 80px from the top of the screen.

scroll-margin-top on the headings Top edge of the か行 heading
0 0px (hidden under the index)
5.5rem 88px (shown just below the index)

According to MDN's scroll-margin-top page, scroll-margin-top sets the top margin kept when an element is brought into view by scrolling. Set the value to match the index height. Whether the index buttons wrap onto two lines depends on the screen width, so check the index height at a smartphone width before you choose the value.

​Posted by 86