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関数ドリル】を毎日やる【勉強用】その3

Posted at

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

##uniq関数の課題内容

uniq関数の挙動
_.uniq([2, 1, 2]);
// => [2, 1]

配列内の重複する値のみ取り除き、新たに出力するもの。
##uniq関数に取り組む前の状態

  • 2回目でやったwithout関数の時に覚えたArray.from(new.set(配列))が使えそうだ
  • すぐにできそう

##uniq関数に取り組んだ後の状態

  • 初めて数分で実装できた
  • 解答のように元の配列は変更していないことの証明もできれば良かった
  • 初めにLodashのuniq関数を見たときに、すぐにArray.fromは思いついたが解説のようなfor文は思いつかなかった
  • forループと反転if文のincludesの組み合わせがすぐに思いつくようになれば、もっと配列を自在に扱えそうだ
  • 短時間でできたのでQiitaの投稿時の装飾について調べられた

##uniq関数の実装コード

const uniq = (array) => {
    const newArray = Array.from(new Set(array));
    return newArray;
};

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

##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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?