Help us understand the problem. What is going on with this article?

javascriptで配列の末尾の要素を格好よく取得する

何とかArray.reduceRight()の使い道がないかなぁと考えていたら思いついたので。

Arrayの末尾が欲しいけど、array[array.length-1]は何か恰好悪いし、
array.pop()だと元の配列が破壊されてしまうからダメと言うシーンに。

コード

const last = array.reduceRight(v => v);

解説

reduceRightに第二引数を与えなかった場合、accumulatorの初期値には末尾の要素がセットされます。
後は第一引数のコールバック関数でaccumulatorをそのまま返し続ければそのまま末尾の要素が結果として返ります。
(空配列に対して呼び出した場合はundefined)

注意事項

逆順にループを回すことになるので計算量的には極めてダメなパターンです。
対象となるArrayの長さが短いことが保証されているシーンだけにしましょう。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away