EN
JavaScript - equivalent to C#/.NET LINQ's Enumerable.First(predicate)
1
answers
6
points
I am looking for an equivalent for the C#/.NET LINQ Enumerable.First(predicate)
method.
I thought using Array
find()
would do the trick, but it doesn't seem to work identically.
My question is, is there anything else I can use?
1 answer
6
points
Try to use Array
findIndex(condition)
.
Here's an example of an arrow function that should work the same way as LINQ's First()
method:
// ONLINE-RUNNER:browser;
const firstItem = (array, condition = () => true) => {
const index = array.findIndex(condition);
if (index === -1) {
throw new Error('Item is not available.');
}
return array[index];
};
// Usage example:
const array = ['a', 'b', 'c', null, undefined];
const item1 = firstItem(array);
const item2 = firstItem(array, (item) => item === 'b');
const item3 = firstItem(array, (item) => item === null);
const item4 = firstItem(array, (item) => item === undefined);
// firstItem(array, (item) => item === 'z'); // it throws exception like C# method
console.log(item1); // a
console.log(item2); // b
console.log(item3); // null
console.log(item4); // undefined
References
0 comments
Add comment