Languages

JavaScript - equivalent to C#/.NET LINQ's Enumerable.First(predicate)

6 points
Asked by:
chelsea
806

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
Answered by:
chelsea
806

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

  1. Array.prototype.findIndex() - JavaScript | MDN
  2. Enumerable.First Method (System.Linq) | Microsoft Docs
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join