0
0

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 3 years have passed since last update.

javascript関数ドリル 初級編flatten関数の実相のアウトプット

Last updated at Posted at 2020-09-11

##flatten関数の課題内容
詳細はこちら
   ↓
https://js-drills.com/blog/flatten/

##flatten関数の取り組む前の状態
全然わからなかった

##flatten関数に取り組んだ後の状態
スプレッド演算子(配列を展開するもの)は配列をコピーして配列で返すものだと勘違いしていたことに気づけた。
json.stringfyが分からなかったです。(よければ教えてください。)

##flatten関数の実装コード(答えを見る前)
分かりませんでした。

##flatten関数の実装コード(答えを見た後)

function flatten(array) {
  const flattendedArray = [];
  for(let i = 0; i < array.length; i++) {
    const value = array[i]
    if( Array.isArray(value) ) {
      flattendedArray.push(...value);
    } else {
      flattendedArray.push(value);
    }
  }

  return flattendedArray;
}

const numbers = [1, [2, [3, [4]], 5]];
const result = flatten(numbers);

console.log( JSON.stringify( result ) );
// => [1, 2, [3, [4]], 5]

console.log( JSON.stringify( numbers ) );
// => [1, [2, [3, [4]], 5]]
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?