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>
);