16
7

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配列の空文字を削除

Last updated at Posted at 2019-05-26

filter()メソッドを使って配列の空文字、nullundefinedを削除する

filter(Boolean)

var arr = ["hoge", "", "123", " ", "0", 123, 0, null, undefined];

arr.filter(Boolean); //["hoge", "123", " ", "0", 123]

// アロー関数式
arr.filter(n => n); //["hoge", "123", " ", "0", 123]

説明

上の使い方をテスト関数を作成して、引数で渡す方式で書くとこうなる

function isTrue(value) {
  return Boolean(value);
}

var arr = ["hoge", "", "123", " ", "0", 123, 0, null, undefined];
arr.filter(isTrue); //["hoge", "123", " ", "0", 123]

filter()はテスト関数がfalseを返す要素は取り除かれる。

この場合は各要素をBooleanに変換すると空文字、nullなどはfalseになるので、取り除かれる。

注意すること

  • Numberの「0」も消えちゃうこと
  • 空白(スペース)は消えないこと

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?