JavaScript filter that stops at the first result

前端 未结 2 767
别那么骄傲
别那么骄傲 2020-12-20 11:33

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

相关标签:
2条回答
  • 2020-12-20 11:52

    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;
    }
    
    0 讨论(0)
  • 2020-12-20 11:54

    You can try .find:

    [7,5,3,2,1].find(x => x % 2 == 0)
    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
    */
    
    0 讨论(0)
提交回复
热议问题