singleOrDefault(defValue)

singleOrDefault(predicate, defValue[, arg])

Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.

Syntax

Parameters

predicate
Type: function(value, key, arg): boolean
A function to test an element for a condition.
defValue
A default value to return.
arg
An external argument.
Return Value

The single element of the input sequence that satisfies the condition, or defValue if no such element is found.

Examples

var fruits1 = [ "orange" ];
var fruit1 = $from(fruits1).singleOrDefault(null);

document.writeln(fruit1);

/*
 This code produces the following output:

 orange
*/

var fruits2 = [];
var fruit2 = $from(fruits2).singleOrDefault(null);

document.writeln(fruit2 == null ? "No such string!" : fruit2);

/*
 This code produces the following output:

 No such string!
*/

var fruits = [ "apple", "banana", "mango", "orange", "passionfruit", "grape" ];

var fruit1 = $from(fruits).singleOrDefault("$length > 10", "");
document.writeln(fruit1);

/*
 This code produces the following output:

 passionfruit
*/

var fruit2 = $from(fruits).singleOrDefault("$length > 15", null);

document.writeln(!fruit2 ? "No such string!" : fruit2);

/*
 This code produces the following output:

 No such string!
*/

Last edited May 18, 2012 at 10:24 AM by suckgamoni, version 1

Comments

No comments yet.