jQuery: Index of element in array where predicate

前端 未结 5 524
小鲜肉
小鲜肉 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:29

    There are no built-in methods for this; the [].indexOf() method doesn't take a predicate, so you need something custom:

    function indexOf(array, predicate)
    {
        for (var i = 0, n = array.length; i != n; ++i) {
            if (predicate(array[i])) {
                return i;
            }
        }
        return -1;
    }
    
    var index = indexOf(arr, function(item) {
        return item.ID == 'foo';
    });
    

    The function returns -1 if the predicate never yields a truthy value.

    Update

    There's Array.findIndex() that you could use now:

    const arr = [{ID: 'bar'}, {ID: 'baz'}, {ID: 'foo'}];
    const index = arr.findIndex(item => item.ID === 'foo');
    console.log(index); // 2

提交回复
热议问题