チャレンジ:sort()によるデータの並べ替えと抽出
メニューを表示するにはスワイプしてください
課題
各オブジェクトがプロパティ(title、author、publicationYear)を持つ本の配列が与えられています。次のタスクを実行するソリューションを作成してください:
- 本の配列をソート:
- タイトルを昇順でソート;
- 著者を降順でソート;
- 出版年を降順でソート。
- 特定のプロパティを個別の配列に抽出:
- タイトルのみを含む配列を作成(タイトル昇順でソート);
- 著者のみを含む配列を作成(著者降順でソート);
- 出版年のみを含む配列を作成(出版年降順でソート)。
元の本の配列は変更しないこと。
123456789101112131415161718192021222324252627282930313233343536const books = [ { title: "Noughts & Crosses", author: "Malorie Blackman", publicationYear: 2001, }, { title: "Priestdaddy", author: "Patricia Lockwood", publicationYear: 2017, }, { title: "The Cost of Living", author: "Deborah Levy", publicationYear: 2018, }, ]; // Sort by `title` in ascending order const sortedByTitleAscending = ___ .sort((a, b) => a.title.___(b.title)) .___((book) => book.title); // Sort by `author` in descending order const sortedByAuthorDescending = [...books] .___((a, b) => b.___.localeCompare(a.___)) .map((book) => book.author); // Sort by `year` in descending order const sortedByYearDescending = [...books] .sort((a, b) => ___ ___ ___) .___((book) => book.publicationYear); console.log("Sorted by Title (Ascending):", sortedByTitleAscending); console.log("Sorted by Author (Descending):", sortedByAuthorDescending); console.log("Sorted by Year (Descending):", sortedByYearDescending);
期待される出力:
Sorted by Title (Ascending): Noughts & Crosses, Priestdaddy, The Cost of Living
Sorted by Author (Descending): Patricia Lockwood, Malorie Blackman, Deborah Levy
Sorted by Year (Descending): 2018, 2017, 2001
- タイトルでのソートには、
localeCompare()プロパティを使いtitleを利用。 - 著者でのソートには、
localeCompare()プロパティを使いauthorを適用。 - 発行年でのソートには、
publicationYearプロパティに基づく数値比較を使用。 - 特定のプロパティを持つ新しい配列を作成するために
map()メソッドを活用。 - 各書籍の目的のプロパティを返す
map()用のコールバック関数を作成。 - タイトル、著者、発行年を抽出する場合、それぞれ
title、author、publicationYearプロパティを返すコールバック関数を使用。 - 元の書籍配列は変更せず、ソートや抽出にはスプレッド構文(
[...books])でコピーを作成。
123456789101112131415161718192021222324252627282930313233343536const books = [ { title: "Noughts & Crosses", author: "Malorie Blackman", publicationYear: 2001, }, { title: "Priestdaddy", author: "Patricia Lockwood", publicationYear: 2017, }, { title: "The Cost of Living", author: "Deborah Levy", publicationYear: 2018, }, ]; // Sort by `title` in ascending order const sortedByTitleAscending = [...books] .sort((a, b) => a.title.localeCompare(b.title)) .map((book) => book.title); // Sort by `author` in descending order const sortedByAuthorDescending = [...books] .sort((a, b) => b.author.localeCompare(a.author)) .map((book) => book.author); // Sort by `year` in descending order const sortedByYearDescending = [...books] .sort((a, b) => b.publicationYear - a.publicationYear) .map((book) => book.publicationYear); console.log("Sorted by Title (Ascending):", sortedByTitleAscending); console.log("Sorted by Author (Descending):", sortedByAuthorDescending); console.log("Sorted by Year (Descending):", sortedByYearDescending);
すべて明確でしたか?
フィードバックありがとうございます!
セクション 5. 章 8
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 5. 章 8