LoginSignup
0
0

More than 3 years have passed since last update.

JS 正の整数なら前からN個、負の整数だったら後ろからN個返す

Posted at

Lodashのnth関数を作成してみた

当初はすごく複雑に考えていた

var array = ["a", "b", "c", "d", "e", "f"]

const nth = (values, selectNum) => {
  if (0 < selectNum) {
    return values[selectNum]
  } else {
    let absolute = Math.abs(selectNum)
    let newArray = []

    for (let i = 0; i < values.length; i++) {
      const array = values.length - (i + 1)
      newArray.push(values[array])
    }

    return newArray[absolute - 1]
  }
}

console.log(nth(array, 3))
// => d

console.log(nth(array, -5))
// => b

もっとシンプルに記述できた

const nth = (values, num) => {
  return 0 < num ? values[num] : values[values.length + num]
}

console.log(nth(array, 3))
// => d

console.log(nth(array, -5))
// => b
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