LoginSignup
0
0

More than 1 year has passed since last update.

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

Posted at

findIndex関数の課題内容

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

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

課題に取り組む前の状態

  • 解答を見ずにできそうだと思った。

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

  • サンプルの処理結果と同じように処理できるものができた。
  • 解答例では変数を定義して第二引数の関数への引数として渡している。どのような関数が第二引数に渡されるのか分からないので、元の配列を破壊されないように、解答例のように変数に代入する方法を取らないといけないと実感。

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

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

var users = [
  { user: "barney", active: true },
  { user: "fred", active: false },
  { user: "pebbles", active: true },
];

const result = findIndex(users, function (o) {
  return o.user == "barney";
});
console.log(result);
// => 0

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

function findIndex(array, predicate, fromIndex = 0) {
  for (let i = fromIndex; i < array.length; i++) {
    const value = array[i];
    if (predicate(value)) {
      return i;
    }
  }
  return -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