LoginSignup
0
0

More than 3 years have passed since last update.

JavaScript の Array で undefined などの値を除外する方法

Last updated at Posted at 2019-09-14

TL;DR

const array = [0, 1, 2, "", undefined, null, NaN, "hoge"]
array.filter(Boolean) // => [1, 2, "hoge"]

詳細

Array.prototype.filter を使用しています。引数に入るコールバックの処理に対して true を返す値のみに絞る関数です。

例えば、以下のように偶数である値のみを抽出したいときなんかにも使えます。

[...Array(10).keys()].filter(n => n % 2 == 0) // => [0, 2, 4, 6, 8]

上記の例の場合は偶数かどうかの処理をはさみましたが、ここに Boolean を入れると Boolean() を実行してくれます。関数呼び出しですね。Boolean() を実行すると値の真偽を判定してくれます。Boolean の仕様によると、以下の値はすべて false と判定されるようです。

false と判定される値

[0, -0, null, false, NaN, undefined, ""]

If the value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

備考

蛇足ですが、new Boolean() でオブジェクトを作るときは false と判定された値を持つ Boolean オブジェクトも生成されるようです。しかも if 文とかで判定するときも常に true が返ってきます。不思議。

const bool = new Boolean(false)
if(bool) console.log("false is true!") // => "false is true!"

参考文献

0
0
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
0
0