2
1

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 1 year has passed since last update.

[JavaScript] flat関数の自作

Last updated at Posted at 2021-12-27

タイトルの通り、flatを自作してみました。

Array.prototype.flat() と同じように depth のデフォルト値を1にしていますが、デフォルト値はundefined か 0 にして無限回まわす方がいいんじゃないかと迷うところです。

const flatFull = (array) => flat(array, 0);

const flatOne = (array) => flat(array, 1)

可読性を高めるには、こんな関数書いておくのもいいのかもな。と迷いつつ。

flatのコード

const flat = (array, depth = 1) => {
  const _flat = (array) => {
    let iOffset = 0;
    for (let i = 0, l = array.length; i < l; i += 1) {
      const element = array[i + iOffset];
      if (Array.isArray(element)) {
        array.splice(i + iOffset, 1, ...element);
        iOffset += element.length - 1;
      }
    }
    return array;
  };
  if (depth <= 0) { depth = Infinity }
  for (let i = 1; i <= depth; i += 1) {
    const arrayLength = array.length;
    _flat(array);
    if (array.length === arrayLength) {
      break;
    }
  }
  return array;
};
console.log(flat([0, 1, 2, [3, 4]]));
// [0, 1, 2, 3, 4]

const arr2 = [0, 1, 2, [[[3, 4]]]];
flat(arr2);
console.log(arr2);
// [ 0, 1, 2, [ [ 3, 4 ] ] ]
flat(arr2);
console.log(arr2);
// [0, 1, 2, [3, 4]]

const arr3 = [[[0, 1], 2], [[[3], 4]]];
flat(arr3);
console.log(arr3);
// [ [ 0, 1 ], 2, [ [ 3 ], 4 ] ]
flat(arr3, 2);
console.log(arr3);
// [ 0, 1, 2, 3, 4 ]

const arr4 = [[[0, 1], 2], [[[3], 4]]];
flat(arr4, 2);
console.log(arr4);
// [ 0, 1, 2, [ 3 ], 4 ]

const arr5 = [[[0, 1], 2], [[[3], 4]]];
flat(arr5, 0);
console.log(arr5);
// [ 0, 1, 2, 3, 4 ]
2
1
5

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?