Feature proposal: Array#indexOf(iterator, i, context)

Skip to first unread message

Rafael Raposo

Jul 21, 2011, 2:47:52 PM7/21/11
to prototy...@googlegroups.com

Don't know if this is going to be of any use for someone or to enter the core, but I needed to write a new indexOf that uses an iterator to get the index from an Array. Array#find finds the value, but I need the index so here is the code if you want to take a look. I know that maybe Array#indexOf will be deprecated for native code use, but I find this version  with iterator quite useful.

    Array.prototype._indexOf = Array.prototype.indexOf;
    function indexOf(itemIt, i, context){
        //not an iterator, uses regular indexOf
        if(!Object.isFunction(itemIt)) {
            return this._indexOf(itemIt, i);

        //item as a function is an iterator
        //NaN 'i' is the context, nullifies 'i' to initialize it correctly after
        if(!Object.isNumber(i)) {
            context = i;
            i = null;

        i || (i = 0);
        var length = this.length;
        if (i < 0) i = length + i;
        for (; i < length; i++)
            if (itemIt.call(context, this[i], i)) {
                return i;
        return -1;
    //redefines indexOf
    Array.prototype.indexOf = indexOf;

I kept the old indexOf for no-iteretor equality cases.

I know that this won't work on a function array if you want the index of a function inside it. Maybe there should/could be an specific indexOfIt() method instead of overriding the regular Array#indexOf method. What do you think?

Reply all
Reply to author
0 new messages