LoginSignup
160

More than 5 years have passed since last update.

[Javascript] 配列から特定の要素を削除する(訂正有り)

Last updated at Posted at 2013-07-11

【訂正】下記方法には重複している要素が削除されないなどの問題があります。詳しくはコメント欄を参照してください。


配列の中から特定の要素を削除したいときはsomeメソッドを使うと便利。

var array1 = [10, 20, 30, 40, 50];
var target = 30;

//要素を削除する
array1.some(function(v, i){
    if (v==target) array1.splice(i,1);    
});

console.log(array1) //=> [10, 20, 40, 50];


/*
 * 連想配列から特定の要素を排除したいときにも便利
 */
var array2 = [
    {id:1, name:"hoge"},
    {id:2, name:"test"},
    {id:3, name:"hello"},
    {id:4, name:"world"},
    {id:5, name:"hoge"},
    {id:6, name:"test"},
    {id:7, name:"hello"}
];

var targetId = 3;
array2.some(function(v, i){
    if (v.id==targetId) array2.splice(i,1); //id:3の要素を削除
});

var targetName = 'hello';
array2.some(function(v, i){
    if (v.name==targetName) array2.splice(i,1);  //name:helloの要素を全て削除
});

TIPS:null埋め、delete、spliceで削除の違い

if (v==target) array1[i] = null; 
//null値が入る。for~inに引っかかる。lengthは変わらない。

if (v==target) delete array1[i]; 
//undefinedが入る。for~inに引っかからない。lengthは変わらない。

if (v==target) array1.splice(i,1);
//完全に削除。for~inに引っかからない。length減る。

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
160