39
31

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 2015-10-10

javascript の配列をループさせずに、任意の文字を削除する方法

  • indexOfで任意の文字列のあるindexを確認。
  • spliceで配列からindexの要素を削除。
  • 注意:配列内の任意の文字列は1つのみ存在すること。
  • ブラウザ IE8以下には対応していません。
var arr = ["aaa","bbb","ccc"];
var val = "bbb"
var idx = arr.indexOf(val);
if(idx >= 0){
 arr.splice(idx, 1); 
}

// arr : ["aaa","ccc"]

filterを使う方法

  • 任意の文字が配列内に複数存在しても、すべて削除できます。
var arr = ["aaa", "bbb", "ccc", "bbb"];
var val = "bbb"
var res = arr.filter(function(a) {
  return a !== val;
});

// res : ["aaa","ccc"]

IE8 を考慮に入れる場合

  • jQuery を使えるなら、$.inArray で対応できます。
// $.inArray(検索文字列, 配列)
var arr = ["aaa","bbb","ccc"];
var idx = $.inArray("bbb", arr);
if(idx >= 0){
 arr.splice(idx, 1); 
}

// arr : ["aaa","ccc"]
39
31
2

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
39
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?