1
1

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 5 years have passed since last update.

JavaScript勉強の記録その11: filterを利用して配列の要素にフィルタをかける

Posted at

filterを利用した配列のデータにフィルタをかける

配列の各要素になんらかの条件をつけてフィルターをかけたい時があるかと思いますが、そのような時にはfilterが役立ちます。
以下の例では2の倍数の数字の場合はtrueを返し、trueの場合はevenNumbersに配列の形で代入し直しています。

index.js
const numbers = [1, 50, 40, 90];

const evenNumbers = numbers.filter(function(number){
  if (number % 2 === 0) {
    return true;
  } else {
    return false;
  }
});
console.log(evenNumbers);
//=> [50, 40, 90]

filterもアロー関数を利用することで大幅に短縮して記述することができます。
if文の部分もざくっと短縮して書くことができます。

index.js
const numbers = [1, 50, 40, 90];

const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers);
//=> [50, 40, 90]
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?