0
0

More than 3 years have passed since last update.

JS 配列の後方最初に一致したindex番号を返す(開始位置も指定できる)

Posted at

lodashのlastIndexOfを作成してみた

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

console.log(lastIndexOf([1, 2, 1, 2], 2))

// =>  3

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

console.log(lastIndexOf([1, 2, 1, 2], 2, 2))
//2番目から『2』の値が最初に一致したindexを返す
// => 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