70

In C#, we have Enumerable.First(predicate). Given this JavaScript code:

function process() {
  var firstMatch = ['a', 'b', 'c'].filter(function(e) {
    return applyConditions(e);
  }).shift();

  if(!firstMatch) {
    return;
  }

  // do something else
}

function applyConditions(element) {
  var min = 97;
  var max = 122;

  var random = Math.floor(Math.random() * (max - min + 1) + min);

  return element === String.fromCharCode(random);
}

other than forEach, using loop, using multiple or operators or implicitly calling some(predicate), is there a smarter way of finding the firstMatch? Preferably a JavaScript function (something like filterFirst(pedicate)) which short-circuits on first match resembling C#'s Enumerable.First() implementation?

FWIW, I am targeting node.js / io.js runtimes.

5 Answers 5

100

No need to reinvent the wheel, the correct way to do it is to use .find:

var firstMatch = ['a', 'b', 'c'].find(applyConditions);

If you're using a browser that does not support .find you can polyfill it

6
  • +1 Yes .find(predicate) is exactly what I am looking for in node.js. This is still experimental and the specification status is draft. Feb 12, 2015 at 15:56
  • 1
    It's not really experimental to be fair :) The draft has settled they're figuring out semantics of other stuff now. Feb 12, 2015 at 17:22
  • 6
    First in c# throws an exception if there wasn't any matching item. So, find is equivalent to FirstOrDefault. Jul 8, 2019 at 13:27
  • BTW, find() returns undefined if no item matches the condition.
    – chri3g91
    Jun 22, 2021 at 6:42
  • As Hamid points out, this is not equivalent to First. This is equivalent to FirstOrDefault, so while this is helpful to someone that's looking for a similar question, it's not really helpful for this question. Jan 7, 2022 at 17:25
6

LINQ users call first and firstOrDefault a lot with no predicate, which is not possible with find. So,

  first() {
    var firstOrDefault = this.firstOrDefault();
    if(firstOrDefault !== undefined)
      return firstOrDefault;
    else
      throw new Error('No element satisfies the condition in predicate.');
  }

  firstOrDefault() {
    return this.find(o => true);
  }
1
  • Or for first truthy value, this.find(o => o).
    – Daniel
    Mar 2, 2021 at 15:50
1

You could emulate this in the case where you want to return the first truthy value with reduce.

['a', 'b', 'c'].reduce(function(prev, curr) { 
    return prev || predicate(curr) && curr; 
}, false);

edit: made more terse with @BenjaminGruenbaum suggestion

5
  • 1
    Dandy! reduce() is pretty close with the exception that it invokes the callback for each element of array (as opposed to short-circuit on first match). Feb 12, 2015 at 12:06
  • @vulcanraven I don't think it does - it's just really confusing to follow - it can be written as return prev || predicate(curr) && curr - also it will fail for falsey array elements (for example finding 0). Feb 12, 2015 at 12:45
  • @BenjaminGruenbaum reduce invokes the callback for the full array always, it doesn't short circuit
    – Esailija
    Feb 12, 2015 at 12:46
  • @Esailija it invokes the callback but it doesn't check against the predicate. Feb 12, 2015 at 12:47
  • @BenjaminGruenbaum, to make it less complicated, consider callback === predicate. It calls the callback for each element and does not short-circuit. Think about array with huge size, where the size of array matters and the complexity of algorithm depends on input array being sorted. Meaning there are use cases where short-circuiting makes a great impact. What I was exactly looking for is .find() which you [described in an answer below].(stackoverflow.com/a/28477788/863980). Now waiting for harmony from ECMAScript 6. :) Feb 12, 2015 at 16:08
1

If you want to create something reusable: Define a predicate type first

declare global {
  type predicate<T> = (arg: T) => boolean;
}

Then define the prototype function on array:

  if (!Array.prototype.First) {
  Array.prototype.First = function <T>(condition: predicate<T>): T {
    let matchingItems: T[] = this.filter((item: T) => {
      if (condition(item))
        return item;
    });
    if (matchingItems === null || matchingItems === undefined || matchingItems.length === 0) {
      throw Error('Invalid operation. No items found.');
    }
    return matchingItems[0];
  }
}

Now you can call the method 'First' on your array and pass in the predicate. Also supported here is any function return a boolean such as your function 'applyConditions'.

1
  • simple but elegant! +1
    – petrosmm
    Jun 22 at 0:33
0

There are a few packages:
linq.js - LINQ for JavaScript https://github.com/mihaifm/linq/
npm install linq

This is a JavaScript implementation of the .NET LINQ library.

It contains all the original .NET methods plus a few additions.

Written in pure JavaScript with no dependencies.

https://www.npmjs.com/package/linq-to-typescript

Implementation of LINQ for TypeScript

await from([bing, google, quackQuackGo])
    .asParallel()
    .selectAsync(downloadHtml)
    .select(getTitle)
    .toArray()

older https://www.npmjs.com/package/linq-typescript

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.