LoginSignup
1
3

More than 1 year has passed since last update.

【JavaScript】値を重複させずに配列をマージする

Posted at

はじめに

キーをもたない配列をマージする際、同じ値が重複してしまいます。
最初から連想配列(オブジェクト)を使えよ!という話な気もするのですが、念のため、通常の配列で値を重複させずにマージする方法をメモとして残します。

問題

配列をマージする際に同じ値が重複してしまう。

array.js
const array1 = [1, 2, 3];
const array2 = [3, 4, 5];
const array3 = [...array1, ...array2];

console.log(array3);
$ node array.js
[ 1, 2, 3, 3, 4, 5 ]

解決策

マージした配列をnew Set([...array1, ...array2])でSetオブジェクトにし、一意な値が格納されるようにします。
さらにArray.fromメソッドでラッピングすることで、オブジェクトから新しいArrayインスタンスを生成します。

array.js
const array1 = [1, 2, 3];
const array2 = [3, 4, 5];
const array3 = Array.from(new Set([...array1, ...array2]));

console.log(array3);
$ node array.js
[ 1, 2, 3, 4, 5 ]

参考資料

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