Array.prototype.last >= 0.1.2

Purpose

Return the last value of the array

Syntax

Array#last ( Numbernr Numberpage= 0 );


Parameters

nr
How many values should be returned
page
From what page they should be returned (The pagesize is the same as the nr of results to return)

Examples

Return the last value

This simply returns the last value, not contained inside an array. This can also be expressed using [arr.length-1]

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.last();>>> 9

Explicitly setting the first value to 1 WILL return an array

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.last(1);>>> [9]

Return the last three values


var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.last(3);>>> [7, 8, 9]

Return paged results

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

arr.last(3, 0);>>> [7, 8, 9]

arr.last(3, 2);>>> [1, 2, 3]

Negative values

When nr is a negative value, all the values are returned except the absolute-of-nr first values.

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

arr.last(-1);>>> [1, 2, 3, 4, 5, 6, 7, 8, 9];

arr.last(-3);>>> [3, 4, 5, 6, 7, 8, 9];

Chaining

last() is incredibly useful for chaining.

Take this unordered array of random numbers, for example:

var arr = [10, 3, 78, 20, 66, 90, 1];

And we want the highest value below 50 (We could use Math.max for this, but we won't)

Without .last method you would need to assign the temporary array to a new variable, in order to get its length later on

// We don't want to modify the original array, so we clone it
var clone = arr.slice();

// We only want numbers below 50
clone = clone.filter(function(a){return a<50});

// Now we want to sort them (we could use Math.max, but for this example we won't)
clone.sort(function(a, b){return a-b});

// And now we can get the last value
clone[clone.length-1];>>> 20

But with last, you can do this

arr.slice().filter(function(a){return a<50}).sort(function(a,b){return a-b}).last();>>> 20

This example looks a bit messy but, yeah, it can be very useful.