3
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.

JSで配列から複数要素を削除する

Last updated at Posted at 2017-04-24

下記のようなsourceからtargetに含まれる要素を削除したいときどうするか。

const source = ['a', 'b', 'c', 'd', 'd', 'e', 'f', 'b'];
const target = ['b', 'd'];

参照は切れてもいい

// filterを使う
const newSource = source.filter((val) => {
  return !target.includes(val);
});

参照はそのままがいい

for (let i = 0; i < source.length; i++) {
  if (target.includes(source[i])) {
    // ポイントはデクリメント
    souce.splice(i--, 1);
  }
}

もっとスマートに書けないかな…

3
7
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
3
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?