0
0

More than 1 year has passed since last update.

【JavaScript関数ドリル】Lodash関数の実装【勉強用】_.lastIndexOf関数

Last updated at Posted at 2022-02-22

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

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

// Search from the `fromIndex`.
_.lastIndexOf([1, 2, 1, 2], 2, 2);
// => 1

配列から第2引数の値を末尾から検索し、最初の値のインデックス番号を返す。
第3引数がある場合は、第3引数の値のインデックス番号の位置から先頭に向かって検索する。

_.lastIndexOf関数の課題内容

_.lastIndexOf関数に取り組む前の状態

  • 配列をarray.length-1からデクリメントし、第2引数と一致するもののインデックス番号を返せばよさそうだ

_.lastIndexOf関数に取り組んだ後の状態

  • 初めて解答とほぼ同じコードを実装できた
  • 一致するものがなければ-1を返すというLodashの説明を見落としていたため、undefinedが返ってくる
  • 普段からドキュメントを読むときに英文を読み飛ばして例文しか見ないため、このようなミスが発生した
  • 引数のデフォルト値の設定の仕方についてよく理解できた

_.lastIndexOf関数の実装コード

const lastIndexOf = (array, value, fromIndex = array.length - 1) => {
    for (let i = fromIndex; 0 <= i; i--) {
        if (value === array[i]) {
            return i;
        };
    };
};

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

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

_.lastIndexOf関数の解答コード

function lastIndexOf(array, value, fromIndex = array.length - 1) {
  for(let i = fromIndex; 0 <= i; i--) {
    if(array[i] === value) {
      return i;
    }
  }

  return -1;
}

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

// Search from the `fromIndex`.
console.log( lastIndexOf([1, 2, 1, 2], 2, 2) );
// => 1
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