Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  75] [ 4]  / answers: 1 / hits: 45679  / 7 Years ago, fri, january 20, 2017, 12:00:00

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?


More From » arrays

 Answers
12

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
*/

[#59280] Wednesday, January 18, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamaal

Total Points: 515
Total Questions: 102
Total Answers: 107

Location: France
Member since Thu, May 6, 2021
3 Years ago
;