LoginSignup
1
0

More than 5 years have passed since last update.

jsで配列を条件分岐で複数要素を削除したい

Last updated at Posted at 2018-02-02

ちょっと悩んだ。ただ、こんなものあまり使わないでしょう。

filterを上手く使おう

js.js
var array = ['hoge','hogehoge','foo','hogege','foo','hogehoge'];
var index_array = [];
var target = 'hogehoge';

array.forEach(function(value,index){
    if(value == target){ 
        // 該当する場合
        index_array.push(index);
    };
});


var newArray = array.filter((value,index) => {
    return !index_array.includes(index);
});

console.log(newArray); // ['hoge','foo','hogege','foo']

forEachで該当するものは、index保存しておいて、後からfilterで処理。

filterはfalseのものを自動でどっかやってくれるので便利りり

追記:もっと楽にできた

index_arrayなんかいらんから、もっと早く書けた。

 var array = ['hoge','hogehoge','foo','hogege','foo','hogehoge'];
 var target = 'hogehoge';
 var newArray = array.filter((value, index) => {
    return value != target;
 });
 console.log(newArray);

@le_panda_noir さんありがとうございます。

const array = ['hoge','hogehoge','foo','hogege','foo','hogehoge'];
const target = 'hogehoge';
const newArray = array.filter(value => value !== target);
console.log(newArray); //  ["hoge", "foo", "hogege", "foo"]

@RikutoYamaguchi さんありがとうございます。

1
0
3

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