LoginSignup
0
0

More than 1 year has passed since last update.

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

Last updated at Posted at 2022-06-05

uniq関数の課題内容

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

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

課題に取り組む前の状態

  • 前回includes関数を覚えたので、この課題については答えを見なくても実装できそうだと思った

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

  • 実際に答えを見なくても実装できた

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

function uniq(arr) {
    const newArr = [];
    for (let i = 0; i < arr.length; i++){
        if (!newArr.includes(arr[i])) {
            newArr.push(arr[i]);
        }
    }
    return newArr;
}

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

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

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

function uniq(array) {
  const uniqArray = [];
  for(let i = 0; i < array.length; i++) {
    const value = array[i];
    if( !uniqArray.includes(value) ) {
      uniqArray.push( value );
    }
  }

  return uniqArray;
}

const numbers = [2, 1, 2];

console.log( uniq(numbers) );
// => [2, 1]

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