LINQ SingleOrDefault() equivalent

You can always use Array.prototype.filter in this way:

const arr = [1, 2, 3];
const [notFoundItem] = arr.filter(id => id === 4); // will contain undefined
const [foundItem] = arr.filter(id => id === 3); // will contain 3

Edit
My answer applies to FirstOrDefault and not to SingleOrDefault.
SingleOrDefault checks if there is only one match and in my case (and in your code) you return the first match without checking for another match.

BTW, if you wanted to achieve SingleOrDefault then you would need to change this:

const item = collection.length < 1 ? null : collection[0];

into

if (collection.length > 1)
   throw "Not single result....";

return collection.length === 0 ? null : collection[0];

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)