3
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】Array.prototype.filter()で条件に一致した配列の要素を削除する方法

Last updated at Posted at 2018-09-06

厳密に言うと、条件に一致しない配列の要素を取得しない処理になる。

例えば配列から偶数を削除する処理を書くとき。
奇数を取得したいのなら条件をval % 2 == 1と書くべきだが、今回は偶数を取得したくないので不等価演算子!を使ってval % 2 != 0と書くことでこの処理が偶数の値を取得したくないという意図を読み取ることができる。

delete_even.js
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const odd = array.filter(val => val % 2 != 0);

console.log(odd); //[1, 3, 5, 7, 9]

条件がval % 2 == 1val % 2 != 0も結果は一緒だけど処理の目的が分かりやすいのは後者だと思う。

3
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
3
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?