Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

lastOrDefault(defValue) , lastOrDefault(predicate, defValue[, arg])

suckgamoni edited this page · 1 revision

Returns the last element of a sequence that satisfies a condition or a default value if no such element is found.

Syntax

Parameters

predicate

Type: function(value, key, arg): boolean
A function to test each element for a condition.

defValue

A default value to return.

arg

An external argument.

Return Value

defValue if the sequence is empty or if no elements pass the test in the predicate function; otherwise, the last element that passes the test in the predicate function.


Example

var daysOfMonth = [];

// Setting the default value to 1 after the query.
var lastDay1 = from(daysOfMonth).lastOrDefault(0);
if (lastDay1 == 0)
{
    lastDay1 = 1;
}
console.log("The value of the lastDay1 variable is " + lastDay1);

// Setting the default value to 1 by using DefaultIfEmpty() in the query.
var lastDay2 = from(daysOfMonth).defaultIfEmpty(1).last();
console.log("The value of the lastDay2 variable is " + lastDay2);

/*
 This code produces the following output:

 The value of the lastDay1 variable is 1
 The value of the lastDay2 variable is 1
*/
var numbers = [ 49.6, 52.3, 51.0, 49.4, 50.2, 48.3 ];

var last50 = from(numbers).lastOrDefault("Math.round($) == 50.0", 0.0);

console.log("The last number that rounds to 50 is " + last50 + ".");

var last40 = from(numbers).lastOrDefault("Math.round($) == 40.0", 0.0);

console.log(
    "The last number that rounds to 40 is " + (last40 == 0.0 ? "[DOES NOT EXIST]" : last40) + ".");

/*
 This code produces the following output:

 The last number that rounds to 50 is 50.2.
 The last number that rounds to 40 is [DOES NOT EXIST].
*/
Something went wrong with that request. Please try again.