LoginSignup
0
0

More than 1 year has passed since last update.

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

Last updated at Posted at 2022-06-05

without関数の課題内容

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

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

課題に取り組む前の状態

  • 引数で、配列の後に複数の値が指定される場合の処理方法が分からない状態ながらもargumentsを使うのかもしれないと思った

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

  • console.logでargumentsの仕組みを確認しながら実装
  • 時間がかかった
  • 解答例を見て、includes関数という便利なものがあることを確認

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

function without(array, values) {
    const newArray = [...arguments[0]];
    let deletedNum = 0;

    for (let i = 0; i < arguments[0].length; i++) {
        for (let j = 1; j < arguments.length; j++) {
            if (arguments[0][i] === arguments[j]) {
                newArray.splice(i-deletedNum, 1);
                deletedNum++;
            }
        }
    }
    return newArray;
}

console.log(without([2, 1, 2, 3], 1, 2));
// => [ 3 ]

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

without関数の実装コード(解答例)

function without(array, ...values) {
  const newArray = [];
  for(let i = 0; i < array.length; i++) {
    const candidateToPush = array[i];
    // values : [1, 2]
    // array: [2, 1, 2, 3]
    // candidateToPush: 2, 1, 2, 3
    if( !values.includes(candidateToPush) ) {
      newArray.push(candidateToPush);
    }
  }

  return newArray;
}

console.log( without([2, 1, 2, 3], 1, 2) );
// => [3]
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