indexOf method in an object array?

前端 未结 27 2474
别跟我提以往
别跟我提以往 2020-11-22 02:18

What\'s the best method to get the index of an array which contains objects?

Imagine this scenario:

var hello = {
    hello: \'world\',
    foo: \'ba         


        
相关标签:
27条回答
  • 2020-11-22 02:54
    var idx = myArray.reduce( function( cur, val, index ){
    
        if( val.hello === "stevie" && cur === -1 ) {
            return index;
        }
        return cur;
    
    }, -1 );
    
    0 讨论(0)
  • 2020-11-22 02:54

    This works without custom code

    var arr, a, found;
    arr = [{x: 1, y: 2}];
    a = {x: 1, y: 2};
    found = JSON.stringify(arr).indexOf(JSON.stringify(a)) > - 1;
    // found === true
    

    Note: this does not give the actual index, it only tells if your object exists in the current data structure

    0 讨论(0)
  • 2020-11-22 02:55

    I did some performance testing of various answers here, which anyone can run them self:

    https://jsperf.com/find-index-of-object-in-array-by-contents

    Based on my initial tests in Chrome, the following method (using a for loop set up inside a prototype) is the fastest:

    Array.prototype.indexOfObject = function (property, value) {
        for (var i = 0, len = this.length; i < len; i++) {
            if (this[i][property] === value) return i;
        }
        return -1;
    }
    
    myArray.indexOfObject("hello", "stevie");
    

    This code is a slightly modified version of Nathan Zaetta's answer.

    In the performance benchmarks I tried it with both the target being in the middle (index 500) and very end (index 999) of a 1000 object array, and even if I put the target in as the very last item in the array (meaning that it it has to loop through every single item in the array before it's found) it still ends up the fastest.

    This solution also has the benefit of being one of the most terse for repeatedly executing, since only the last line needs to be repeated:

    myArray.indexOfObject("hello", "stevie");
    
    0 讨论(0)
提交回复
热议问题