find the array index of an object with a specific key value in underscore

前端 未结 12 2398
暖寄归人
暖寄归人 2020-12-05 09:12

In underscore, I can successfully find an item with a specific key value

var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ r         


        
12条回答
  •  再見小時候
    2020-12-05 09:40

    Keepin' it simple:

    // Find the index of the first element in array
    // meeting specified condition.
    //
    var findIndex = function(arr, cond) {
      var i, x;
      for (i in arr) {
        x = arr[i];
        if (cond(x)) return parseInt(i);
      }
    };
    
    var idIsTwo = function(x) { return x.id == 2 }
    var tv = [ {id: 1}, {id: 2} ]
    var i = findIndex(tv, idIsTwo) // 1
    

    Or, for non-haters, the CoffeeScript variant:

    findIndex = (arr, cond) ->
      for i, x of arr
        return parseInt(i) if cond(x)
    

提交回复
热议问题