lastOrDefault(defValue)

lastOrDefault(predicate, defValue[, arg])

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.

Examples

var daysOfMonth = [];

// Setting the default value to 1 after the query.
var lastDay1 = $from(daysOfMonth).lastOrDefault(0);
if (lastDay1 == 0)
{
    lastDay1 = 1;
}
document.writeln("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();
document.writeln("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);

document.writeln("The last number that rounds to 50 is " + last50 + ".");

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

document.writeln(
	"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].
*/

Last edited May 17, 2012 at 8:55 AM by suckgamoni, version 3

Comments

No comments yet.