駆け出しのエンジニア日記

プログラミング言語勉強中の奮闘日記

filterメソッド

提供されたコールバック関数を満たす要素からなる新しい配列を生成します。

実際にサンプルを見てみましょう。

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
numbers.filter((num) => {
return num === 4;
})
// [4]

1~10が入った配列があります。filterメソッドを用いて実行すると、条件に合致するのは4のみなので [4] の配列が新しく生成されています。

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
numbers.filter((num) => {
return num < 7;
})
// [1,2,3,4,5,6]

7よりも小さい値を出力したい時は1~6が入った配列が新しく生成されます。

もう一つサンプルを見てみます。

const movies = [
{
title: 'Amadeus',
score: 99,
year: 1984
},
{
title: 'Sharknado',
score: 35,
year: 2013
},
{
title: '13 Going On 30',
score: 70,
year: 2004
},
{
title: 'Stand By Me',
score: 85,
year: 1986
},
{
title: 'Waterworld',
score: 62,
year: 1995
},
{
title: 'Jingle All The Way',
score: 71,
year: 1996
},
{
title: 'Parasite',
score: 95,
year: 2019
},
{
title: 'Notting Hill',
score: 77,
year: 1999
},
{
title: 'Alien',
score: 90,
year: 1979
}
];

※映画のscoreはあくまでサンプルです。

・scoreが80以上のものに絞りたい場合

const goodMovies = movies.filter(movie => movie.score > 80);
// {title: 'Amadeus', score: 99, year: 1984}
// {title: 'Stand By Me', score: 85, year: 1986}
// {title: 'Parasite', score: 95, year: 2019}
// {title: 'Alien', score: 90, year: 1979}

このように4つ出力できます。

省略する前は下記です。

const goodMovies = movies.filter(movie => {
return movie.score > 80;
});

・2010年より後に公開された映画に絞りたい場合

const recentMovies = movies.filter(movie => movie.year > 2010);
// {title: 'Sharknado', score: 35, year: 2013}
// {title: 'Parasite', score: 95, year: 2019}

 

また以前記述したmapメソッドとも組み合わせることが可能です。

・score80以上の映画のタイトルだけ知りたい場合

const goodMovieTitles = movies
.filter(movie => movie.score > 80)
.map(movie => movie.title);
 
// (4) ['Amadeus', 'Stand By Me', 'Parasite', 'Alien']

4つの新しい配列が作られていることがわかります。

 

便利に使うことができるので覚えておきましょう。