firstOrDefault(defValue)

firstOrDefault(predicate, defValue[, arg])

Returns the first element of the 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
Default value to return.
arg
An external argument.
Return Value

defValue if source is empty or if no element passes the test specified by predicate; otherwise, the first element in source that passes the test specified by predicate.

Examples

var numbers = [ ];
var first = $from(numbers).firstOrDefault(0);
document.writeln(first);

/*
 This code produces the following output:

 0
*/

var names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu" ];

var firstLongName = $from(names).firstOrDefault("$length > 20", "");

document.writeln("The first long name is '" + firstLongName + "'.");

var firstVeryLongName = $from(names).firstOrDefault("$length > 30", null);

document.writeln(
	"There is " + (firstVeryLongName == null ? "not a" : "a") + " name longer than 30 characters.");

/*
 This code produces the following output:

 The first long name is 'Andersen, Henriette Thaulow'.
 There is not a name longer than 30 characters.
*/

Last edited May 17, 2012 at 9:54 AM by suckgamoni, version 3

Comments

No comments yet.