LoginSignup
1
4

More than 3 years have passed since last update.

【JS】2次元配列を1次元にする方法。reduce & concatで多次元配列の次元を1つ下げる方法。

Posted at

reduceとconcatを使うことで2次元配列を1次元にすることができる。

できること

[[1,2], [3,4]]のような配列を、内側のカッコを外して[1,2,3,4]とすることができる。

実例

arr = [[1, 2], [3, 4], [5, 6]]

res = arr.reduce( (newArr,elem) => {
  return  newArr.concat(elem)
}, [] )

console.log(res)   //[1, 2, 3, 4, 5, 6]
console.log(arr)   //[[1, 2], [3, 4], [5, 6]] 非破壊
  • 配列.reduce( (処理結果, 要素) => 処理, 初期値 )

    • reduceは指定した配列の要素を一つづつ取り出し、記述した処理を実行し、最後の処理結果を返す。(値は一つ)
    • 第1引数が処理結果、第2引数が配列の一つ一つの要素が入る変数。
    • 処理の後ろに「 , 」をつけて処理結果の初期値を指定できる。
      • newArrの初期値を空の配列にしている。
    • reduceは非破壊処理。
    • 元の配列はそのまま。(上記ではarr)
    • 処理結果を代入する変数を用意。(上記ではres)
  • 配列.concat(要素)

    • concatは指定した配列の後ろに要素を足す

▼上記処理を段階的におうと以下のようになる

処理回数 newArr elem 処理結果
1 [] [1, 2] [1, 2]
2 [1, 2] [3, 4] [1, 2, 3, 4]
3 [1, 2, 3, 4] [5, 6] [1, 2, 3, 4, 5, 6]

よって、最終的に [1, 2, 3, 4, 5, 6] が返る。


returnの有無

reduceの処理で{ }をつける場合はreturnが必要。ない場合は不要となる。

return必須
res = arr.reduce( (newArr,elem) => {
  return  newArr.concat(elem)
}, [] )

↑↓ どちらも同じ処理

return不要
res = arr.reduce( (newArr,elem) => 
   newArr.concat(elem)
, [] )

これは、アロー関数で処理結果が一つの値のみを返す場合{ return }が省略可能なため。

処理結果の中に複数の式が入る場合や、処理が長く塊が見にくい場合などに、{ }を使う。


多次元配列の場合

reduce & concatは多次元配列でも利用できる。
多次元配列の場合は、各の要素の [ ]を一つ取り除く(次元を一つ下げる)処理となる。

3次元→2次元
arr = [[[1,2]],[[3,4],[5,6]]]

res = arr.reduce( (newArr,elem) => 
   newArr.concat(elem)
, [] )

console.log(res) //[[1,2],[3,4],[5,6]]



▼3次元を1次元にする

3次元配列を1次元にしたい場合は、reuduce & concatの処理結果に、再度reduce & concatをかければいい。

arr = [[[1,2]],[[3,4],[5,6]]]

res = arr.reduce( (newArr,elem) => 
            newArr.concat(elem), [] 
            ).reduce( (newArr2, elem2) => 
            newArr2.concat(elem2), [] )

console.log(res) //[1, 2, 3, 4, 5, 6]


異なる次元の要素が含まれる場合

異なる次元の要素が混在していてもreduceは使用可能。

この場合、reduce & concat 1回につきカッコが一つ外れる。カッコがない要素はそのまま出力される。

▼例

[1, [2,3,[4,5]],[6,7,[8,9],10]]

 ↓ reduce & concat

[1, 2, 3, [4, 5], 6, 7, [8, 9], 10]

arr2 = [1, [2,3,[4,5]],[6,7,[8,9],10]]

res2 = arr2.reduce( (newArr,elem) => 
   newArr.concat(elem)
, [] )

console.log(res2) //[1, 2, 3, [4, 5], 6, 7, [8, 9], 10]

▼処理の流れ

処理回数 newArr elem 処理結果
1 [] 1 [1]
2 [1] 2, 3, [4, 5] [1, 2, 3, [4, 5]]
3 [1, 2, 3, [4, 5]] 6, 7, [8, 9], 10 [1, 2, 3, [4, 5], 6, 7, [8, 9], 10]
1
4
4

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
4