Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

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

suckgamoni edited this page · 1 revision

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.


Example

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

console.log(fruit1);

/*
 This code produces the following output:

 orange
*/

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

console.log(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", "");
console.log(fruit1);

/*
 This code produces the following output:

 passionfruit
*/

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

console.log(!fruit2 ? "No such string!" : fruit2);

/*
 This code produces the following output:

 No such string!
*/
Something went wrong with that request. Please try again.