find the array index of an object with a specific

2019-01-14 00:00发布

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){ return voteItem.id == voteID; });
//data = { id: 2 }

but how do I find what array index that object occurred at?

10条回答
在下西门庆
2楼-- · 2019-01-14 00:10

This is to help lodash users. check if your key is present by doing:

hideSelectedCompany(yourKey) {
 return _.findIndex(yourArray, n => n === yourKey) === -1;
}
查看更多
smile是对你的礼貌
3楼-- · 2019-01-14 00:16

If your target environment supports ES2015 (or you have a transpile step, eg with Babel), you can use the native Array.prototype.findIndex().

Given your example

const array = [ {id:1}, {id:2} ]
const desiredId = 2;
const index = array.findIndex(obj => obj.id === desiredId);
查看更多
倾城 Initia
4楼-- · 2019-01-14 00:17

If you want to stay with underscore so your predicate function can be more flexible, here are 2 ideas.

Method 1

Since the predicate for _.find receives both the value and index of an element, you can use side effect to retrieve the index, like this:

var idx;
_.find(tv, function(voteItem, voteIdx){ 
   if(voteItem.id == voteID){ idx = voteIdx; return true;}; 
});

Method 2

Looking at underscore source, this is how _.find is implemented:

_.find = _.detect = function(obj, predicate, context) {
  var result;
  any(obj, function(value, index, list) {
    if (predicate.call(context, value, index, list)) {
      result = value;
      return true;
    }
  });
  return result;
};

To make this a findIndex function, simply replace the line result = value; with result = index; This is the same idea as the first method. I included it to point out that underscore uses side effect to implement _.find as well.

查看更多
女痞
5楼-- · 2019-01-14 00:22

I don't know if there is an existing underscore method that does this, but you can achieve the same result with plain javascript.

Array.prototype.getIndexBy = function (name, value) {
    for (var i = 0; i < this.length; i++) {
        if (this[i][name] == value) {
            return i;
        }
    }
    return -1;
}

Then you can just do:

var data = tv[tv.getIndexBy("id", 2)]

查看更多
狗以群分
6楼-- · 2019-01-14 00:23

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)
查看更多
Root(大扎)
7楼-- · 2019-01-14 00:25

you can use indexOf method from lodash

var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
var index=_.indexOf(tv,data);
查看更多
登录 后发表回答