Getting index of an array's element based on its properties

后端 未结 7 1108
名媛妹妹
名媛妹妹 2020-11-27 17:17

I have a JavaScript array of objects like this:

var myArray = [{...}, {...}, {...}];

Each object has unique id among other pro

相关标签:
7条回答
  • 2020-11-27 17:24

    You can use .reduce(), which lets you reduce an Array down to a single value.

    var obj_idx = myArray.reduce(function(idx, item, i) {
      return item.id === 4 ? i : idx;
    }, -1);
    

    The -1 is a default value if no match is found.


    If you have multiple uses for this, you may want to make a function factory.

    function idxForID(target) {
        return function(idx, item, i) {
          return item.id === target ? i : idx;
        };
    }
    

    And then use it like this.

    var obj_idx = myArray.reduce(idxForID(4), -1);
    
    0 讨论(0)
  • 2020-11-27 17:29

    If each id is unique, you can do it like this:

    o1 = {id:1}
    o2 = {id:2}
    o3 = {id:3}
    o4 = {id:4}
    a = [o1,o2,o3,o4]
    a.indexOf( a.filter( function(i){return i.id==4} )[0] );
    
    0 讨论(0)
  • 2020-11-27 17:35

    You could also try a recursive function, though @xdazz's looks rather attractive.

    var indexOfId = function(arr, id, index) {
        if (!index) { index = 0; }
        if (arr[index].id == id) {
          return index;
        }
        return ((index += 1) >= arr.length) ? -1 : indexOfId(arr, id, index);
    };
    
    0 讨论(0)
  • 2020-11-27 17:39
    var index = myArray.map(function(el) {
      return el.id;
    }).indexOf(4);
    

    For IE below version 9, map need a patch, or just use a loop.

    0 讨论(0)
  • 2020-11-27 17:46

    ES6 Array.findIndex

    const myArray = [{id:1}, {id:2}, {id3}];
    const foundIndex = myArray.findIndex((el) => (el.id === 3));
    
    0 讨论(0)
  • 2020-11-27 17:49

    Why not simply make a loop ?

    function indexOfId(array, id) {
        for (var i=0; i<array.length; i++) {
           if (array[i].id==id) return i;
        }
        return -1;
    }
    

    The fact that there are many facilities in js (or js libraries) doesn't mean you must not, sometimes, write a loop. That's fast and simple.

    0 讨论(0)
提交回复
热议问题