1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

絞り込み機能をfilter関数で作るチュートリアル

Last updated at Posted at 2023-10-19

初めに

ホームページのお知らせにある年次のボタンをクリックすると、
対象のお知らせが表示される絞り込み機能を実装しました。

コード

HTML

各ボタンにデータ属性でdata-yearで値を持たせています。
お知らせについては、今回はJSのデータ構造の理解を深めるためにHTMLに埋め込みませんでした。

index.html

<button data-year="all">All</button>
<button data-year="2021">2021</button>
<button data-year="2022">2022</button>
<button data-year="2023">2023</button>

<ul class="news">
         
</ul>

JavaScript

クリックしたボタンのデータ属性がallなら全件表示して、all以外ならfilter関数でnewsList配列のyearプロパティと一致したオブジェクトを抽出してHTMLにレンダリングしています。

script.js

const newsList = [
    {title: "ニュース1", year: 2021},
    {title: "ニュース2", year: 2022},
    {title: "ニュース3", year: 2023},
    {title: "ニュース4", year: 2021},
    {title: "ニュース5", year: 2022},
]

const info = document.querySelector('.news');

// newsListをHTMLに表示したい
newsList.map((news) => {
    const li   = document.createElement('li');
    li.textContent = news.title;
    info.appendChild(li);
})

document.querySelectorAll('.btn').forEach((btn) => {
    btn.addEventListener('click', () => {
        filterNews(btn.dataset.year);
    })
})

function filterNews(yearStr) {
    // クリックしたボタンのデータ属性が all なら お知らせを全件表示
    if (yearStr === "all") {
        renderList(newsList)
    } else {
        // all 以外なら クリックしたボタンのデータ属性と同じnewsList配列のyearプロパティを持つオブジェクトを抽出してrenderList関数の引数に渡す
        renderList(newsList.filter((news) => news.year == yearStr));
    }
}

function renderList(filters) {
    info.innerHTML = filters.map(news => `<li>${news.title}</li>`).join("")
}

終わりに

同じことをやるにしても、色々な方法があるので状況に応じて組み合わせていきたいと思います。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?