Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript filter that stops at the first result

Is there a mechanism in JavaScript (without having to write my own) similar to filter. Instead of returning all the filtered elements of a collection though, it only returns the first one. Of course I could do the following to get the first even number:

[7,5,3,2,1].filter(x => x % 2 == 0)[0] 

But if there were 10 million more numbers in that list, there'd be a lot of unnecessary work. In a language like Haskell, the other 10 million numbers wouldn't be looked at due to lazy evaluation.

Is there a mechanism in JavaScript to do the above without evaluating any elements after the first result?

like image 643
at. Avatar asked Jan 20 '17 01:01

at.


People also ask

Does JavaScript filter preserve order?

Yes, the . filter() method returns a new array, without the filtered elements in the same order as initially. The order of the elements is one of the main feature of a array.

What does .filter do in JavaScript?

The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.

Does filter always return an array?

filter always returns an array (array of all the filtered items), use array. find to get the single object. please change your title, because you get an array as result of filter .


2 Answers

You can try .find:

[7,5,3,2,1].find(x => x % 2 == 0); // result: 2 

From the docs:

The find() method returns a value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

Simple benchmark

var arr = [...Array(10000)].map( (item, idx) => idx )  arr.filter(i => i == 3000)[0] arr.find(i => i == 3000)  /*   arr.filter x 1,358 ops/sec ±0.40% (91 runs sampled)   arr.find x 23,743 ops/sec ±0.40% (90 runs sampled)   Fastest is arr.find */ 
like image 137
mrlew Avatar answered Sep 28 '22 09:09

mrlew


I think Array.prototype.find() accomplishes this - it will retrieve the first element in an array that matches a certain criteria:

[7, 5, 3, 2, 1].find(isEvenNumber); //2  function isEvenNumber(elem) {   return elem % 2 === 0; } 
like image 21
hackerrdave Avatar answered Sep 28 '22 10:09

hackerrdave