2
2

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 3 years have passed since last update.

JS 配列の後ろからN個返す

Last updated at Posted at 2020-07-21

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

メソッド使用せずに作成した場合

const takeRight = (array = [], takeRightNum = 1) => {
  if (takeRightNum === 0) {
    return []
  }

  if (array.length < takeRightNum) {
    return [...array]
  }

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

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

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

console.log(takeRight([1, 2, 3], 0))
// => []

console.log(takeRight([1, 2, 3], 5))
// => [1, 2, 3]

sliceメソッドで作成した場合

sliceメソッドとは

  • の引数に抜き出す範囲を指定すると、新しい配列オブジェクトとして返します
  • マイナス数字だと後ろから順に選択する

▼以下の記事を参考にさせて頂きました
suin: JavaScriptで配列の後ろからN個の要素を取り出す


const takeRight = (array = [], takeRight = 1) => {
  if (takeRight === 0) {
    return []
  }
  return array.slice(-takeRight)
}
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?