LoginSignup
0
0

More than 3 years have passed since last update.

JS 配列からN個返す

Posted at

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

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

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

  const newArray = []
  for (let i = 0; i < take; i++) {
    newArray.push(array[i])
  }

  return newArray
}

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

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

console.log(take([1, 2, 3], 5))
=> [1, 2, 3]
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