Is there an indexOf in javascript to search an array with custom compare function

后端 未结 8 1743
执笔经年
执笔经年 2020-12-05 18:05

I need the index of the first value in the array, that matches a custom compare function.

The very nice underscorej has a \"find\" function that returns the

8条回答
  •  生来不讨喜
    2020-12-05 18:16

    using underscore I came up with something copied from their find implementation using _.any:

    findIndex = function (obj, iterator, context) {
        var idx;
        _.any(obj, function (value, index, list) {
            if (iterator.call(context, value, index, list)) {
                idx = index;
                return true;
            }
        });
        return idx;
    };
    

    What do you think - do you have any better solutions?

提交回复
热议问题