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

【JavaScript 関数ドリル】中級編のpullAt関数の実装アウトプット

Posted at

pullAt関数の課題内容

_. pullAt関数を自分で実装する課題。
https://lodash.com/docs/4.17.15#pullAt

「課題内容」/「解説動画」/「解答例」を確認したい場合は、以下リンク先のページを参照。
https://js-drills.com/blog/pullAt/

課題に取り組む前の状態

  • 前回取り組んだpull関数と同じように実装すればいいのかなと思った。

課題に取り組んだ後の状態

  • サンプルの実行結果と同じ結果が出たものの、第二引数が数字の場合、複数渡される可能性があることに気づいていなかったため、解答例を見て、修正しなければならなかった。

pullAt関数の実装コード(答えを見る前)

function pullAt(array, indexes) {
    const pulledArray = [];
    
    switch (typeof (indexes)) {
        case 'number':
            pulledArray.push(array.splice(indexes, 1));
        case 'object':
            // indexes.sort();
            for (let i =  indexes.length-1; i >=0; i--) {
                pulledArray.unshift(...array.splice(indexes[i], 1));
            }
    }

  return pulledArray;
}

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

function pullAt(array, ...indexes) {
  const pulledArray = [];
  const indexArray = Array.isArray(indexes[0]) ? indexes[0] : indexes;

    for (let i = 0; i < indexArray.length; i++) {
        pulledArray.push(array[indexArray[i]]);
    }
    indexArray.sort();
    for (let i = indexArray.length - 1; 0 <= i; i--) {
        array.splice(indexArray[i], 1);
    }

  return pulledArray;
}
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?