Count number of values in array between two input values

前端 未结 4 1788
鱼传尺愫
鱼传尺愫 2021-01-28 17:05

As the title suggests, I want to create a function the counts the number of values in my array between two values that have been entered by the user. So for example, if the arra

4条回答
  •  花落未央
    2021-01-28 17:10

    You can create an extremely clean solution to this problem by utilizing the second property of Array#filter (which sets the this binding given to your callback of choice):

    var array = [1, 4, 6, 7, 8, 6]
    
    function inRange (x) {
      return this[0] <= x && x <= this[1]
    }
    
    var result = array.filter(inRange, [5, 7]).length
    
    console.log('Total number of values:', result)

提交回复
热议问题