underscore icon indicating copy to clipboard operation
underscore copied to clipboard

_.indexOf doesn't work on arrays of objects

Open zetlen opened this issue 14 years ago • 15 comments

_.indexOf doesn't use _.isEqual for its test, so you can't look up the index of an object in an array. var a = [{23:'hello'},{283:'goodbye'}], b = {283:'goodbye'};

_.indexOf(a,b); // produces -1

I propose the following change to _.indexOf.

old version

indexOf: function (array, item, isSorted) {
    if (array == null) return -1;
    var i, l;
    if (isSorted) {
      i = _.sortedIndex(array, item);
      return array[i] === item ? i : -1;
    }
    if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
    for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
    return -1;
  }

New version uses an optional deepEquality flag. Deep equality test cannot use nativeIndexOf and is significantly slower.

indexOf: function (array, item, isSorted, deepEquality) {
    var eqfn = deepEquality ? _.isEqual : function (a, b) { return a === b };
    if (array == null) return -1;
    var i, l;
    if (isSorted) {
        i = _.sortedIndex(array, item);
        return eqfn(array[i], item) ? i : -1;
    }
    if (!deepEquality && nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
    for (i = 0, l = array.length; i < l; i++) if (i in array && eqfn(array[i], item)) return i;
    return -1;
}

zetlen avatar Apr 14 '12 19:04 zetlen

The change to indexOf will break compatibility with the native Array#indexOf, though...it doesn't use isEqual internally, and there's no way to specify a custom comparison function.

ghost avatar Apr 14 '12 20:04 ghost

Can you clarify why you chose to rewrite _.indexOf instead of modifying _.intersection?

octatone avatar Apr 15 '12 00:04 octatone

I did make a mistake in my proposed code. Doing the deep equality check would mean you couldn't use the native Array.prototype.indexOf, so that's a definite performance concern. I'd say there should definitely be some kind of deepEquality flag.

I also made a mistake in naming the issue! I discovered this when trying to use .intersection, but it's more properly a missing feature in .indexOf. Here's my proposed update.

indexOf2: function (array, item, isSorted, deepEquality) {
    var eqfn = deepEquality ? _.isEqual : function (a, b) { return a === b };
    if (array == null) return -1;
    var i, l;
    if (isSorted) {
        i = _.sortedIndex(array, item);
        return eqfn(array[i], item) ? i : -1;
    }
    if (!deepEquality && nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
    for (i = 0, l = array.length; i < l; i++) if (i in array && eqfn(array[i], item)) return i;
    return -1;
}

Passing the flag through all the methods that use .indexOf would obviously require a more extensive refactor, but you get the basic idea.

zetlen avatar Apr 15 '12 00:04 zetlen

Modified the original post to reflect this.

zetlen avatar Apr 15 '12 00:04 zetlen

JavaScript uses object identity equality, not deep equality. Underscore follows suit. isEqual is a special-case function. The rest of Underscore shouldn't use its equality semantics by default.

jashkenas avatar Apr 18 '12 18:04 jashkenas

I agree with you that object identity equality should be the default! I was at least hoping for a flag one could set that would use isEqual.

zetlen avatar Apr 18 '12 18:04 zetlen

+1 for suggestion made by @zetlen, deep Equality comparison of objects within an array would be very useful.

paulbjensen avatar Apr 24 '12 18:04 paulbjensen

+1

kendagriff avatar Nov 26 '12 13:11 kendagriff

Best not to extend the semantics of indexOf due to conflicts with Array::indexOf—you can use something like this, though:

_.mixin({
  'deepIndex': function (array, item) {
    var result = -1;
    _.some(array, function (value, index) {
      if (_.isEqual(value, item)) {
        result = index;
        return true;
      }
    });
    return result;
  }
});

ghost avatar Nov 26 '12 15:11 ghost

Thanks, I basically did just that.

kendagriff avatar Nov 26 '12 16:11 kendagriff

If we are going to do everything the way JavaScript does by default, why not just delete the underscore.js library then?

bravadomizzou avatar Jun 17 '13 13:06 bravadomizzou

Really bravadomizzou? It provides fallbacks for browsers that don't support it and provides some extra functionality that default javascript doesn't have.

jakecraige avatar Jan 05 '14 17:01 jakecraige

I wonder why the following two samples work differently:

var a = [{23:'hello'},{283:'goodbye'}] , b = {283:'goodbye'}; console.log(b); console.log(_.indexOf(a,b)); // returns -1

var c = .findWhere(a, {283:'goodbye'}); console.log(c); console.log(.indexOf(a,c)); // returns 1

I have created a fiddle here: http://jsfiddle.net/rjcXL/1/

tapsboy avatar Jan 07 '14 18:01 tapsboy

@tapsboy It's the same reason

({a: 1}) === ({a: 1});

is false, but

({a: 1}).a === ({a: 1}).a;

is true. The first is comparing references while the second is comparing values.

caseywebdev avatar Jan 07 '14 19:01 caseywebdev

I encountered the same issue, I used _.findWhere instead of _.indexOf. Thanks.

rtorino avatar Mar 11 '14 16:03 rtorino