iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0

Day17 要做的是幫列表排序,但要忽略開頭的定冠詞

資料

const bands: string[] = [
  "The Plot in You",
  "The Devil Wears Prada",
  "Pierce the Veil",
  "Norma Jean",
  "The Bled",
  "Say Anything",
  "The Midway State",
  "We Came as Romans",
  "Counterparts",
  "Oh, Sleeper",
  "A Skylit Drive",
  "Anywhere But Here",
  "An Old Dog",
];


  const [sortedBands, setSortedBands] = useState<string[]>(bands);
  const [isSorted, setIsSorted] = useState<boolean>(false);

排序

const strip = (bandName: string): string => {
  return bandName.replace(/^(a |the |an )/i, "").trim();
};
  const handleSort = () => {
    if (!isSorted) {
      const sorted = [...bands].sort((a, b) =>
        strip(a).localeCompare(strip(b))
      );
      setSortedBands(sorted);
      setIsSorted(true);
    } else {
      setSortedBands(bands);
      setIsSorted(false);
    }
  };

畫面結構

  return (
    <div className="p-6 max-w-md mx-auto bg-white rounded-xl shadow-md">
      <h2 className="text-xl font-bold mb-4 text-gray-800">Band Names</h2>

      <button
        type="button"
        onClick={handleSort}
        className="mb-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
      >
        {isSorted ? "Unsort" : "Sort"} Bands
      </button>

      <ul className="list-none p-0">
        {sortedBands.map((band, index) => (
          <li
            key={index}
            className="py-2 px-4 bg-gray-100 mb-2 rounded-md text-gray-800 hover:bg-gray-200 transition-colors"
          >
            {band}
          </li>
        ))}
      </ul>
    </div>
  );

DEMO

https://codesandbox.io/p/devbox/6pvq8v


上一篇
[Day16]_Mouse-Move-Shadow
系列文
React30——用 React 探索 JavaScript30 的魅力17
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言