jQuery: Index of element in array where predicate

前端 未结 5 530
小鲜肉
小鲜肉 2020-12-20 13:51

I have an array of objects. Each object has, among others, an ID attribute. I want to find the index in the array of the object with a specific ID. Is there any elegant and

5条回答
  •  青春惊慌失措
    2020-12-20 14:12

    See [`Array.filter`][1] to filter an array with a callback function. Each object in the array will be passed to the callback function one by one. The callback function must return `true` if the value is to be included, or false if not.
    
        var matchingIDs = objects.filter(function(o) {
            return o.ID == searchTerm;
        });
    
    All objects having the ID as searchTerm will be returned as an array to matchingIDs. Get the matching element from the first index (assuming ID is unique and there's only gonna be one)
    
        matchingIDs[0];
    
      [1]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
    

    Update:

    Checkout findIndex from ECMAScript 6.

    items.findIndex(function(item) { item.property == valueToSearch; });
    

    Since findIndex isn't available on most browsers yet, you could backfill it using this implementation:

    if (!Array.prototype.findIndex) {
      Array.prototype.findIndex = function(predicate) {
        if (this == null) {
          throw new TypeError('Array.prototype.findIndex called on null or undefined');
        }
        if (typeof predicate !== 'function') {
          throw new TypeError('predicate must be a function');
        }
        var list = Object(this);
        var length = list.length >>> 0;
        var thisArg = arguments[1];
        var value;
    
        for (var i = 0; i < length; i++) {
          value = list[i];
          if (predicate.call(thisArg, value, i, list)) {
            return i;
          }
        }
        return -1;
      };
    }
    

提交回复
热议问题