51
26

More than 5 years have passed since last update.

Javascriptで配列をマージする

Last updated at Posted at 2018-08-23

Javascriptで2つの配列をマージしたいことがあると思います。

配列Aと配列Bを、どちらの配列の値も残したまま連結する場合は以下のように記述できます。

let array_base = ['blue', 'green', 'yellow'];
let array_add = ['red', 'white'];
let result_concat = array_base.concat(array_add);
console.log(result_concat);

上記の結果は以下となります。

["blue", "green", "yellow", "red", "white"]
0:"blue"
1:"green"
2:"yellow"
3:"red"
4:"white"


Object.assignを使った場合、思い通りにならないかもしれません。

let array_base = ['blue', 'green', 'yellow'];
let array_add = ['red', 'white'];
let result_assign = Object.assign(array_base, array_add);
console.log(result_assign);

上記の結果は以下となります。
キーが重複する部分は第二引数の配列の値で上書きされてしまいます。

["red", "white", "yellow"]
0:"red"
1:"white"
2:"yellow"



pushを使った場合は配列の最後に配列が追加されます。

let array_base = ['blue', 'green', 'yellow'];
let array_add = ['red', 'white'];
array_base.push(array_add);
console.log(array_base);

上記の結果は以下となります。

["blue", "green", "yellow", Array(2)]
0:"blue"
1:"green"
2:"yellow"
3:(2) ["red", "white"]
51
26
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
51
26