2

Is there a way to get Array.prototype.includes() to also work with non-primitive objects by supplying a equals+hash predicate?

For example given a list:

var list = [{id:111},{id:222},{id:333}];

console.log(list.includes({id:333});
// output: false

From the above example it looks like equality is done by object identity (i.e. memory address) and not by value which makes, of course, total sense and is expected. But is there a way to supply an equality function to list.includes() so that the primitive value of id is used to determine equality?

The Arrays.includes() documentation does not mention anything about accepting an equality predicate.

ccpizza
  • 28,968
  • 18
  • 162
  • 169

1 Answers1

6

Array#includes takes two parameters:

searchElement: The value to search for.

fromIndex (Optional): The position in this array at which to begin searching for searchElement.

You can use Array#some instead:

const list = [{id:111},{id:222},{id:333}];

console.log( list.some(({id}) => id === 333) );
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • Awesome! Thanks! It's unexpected though that a separate method `some()` was introduced rather than having `includes()` accept an optional predicate; to me, logically, `some()` is the same as `includes()`. – ccpizza Aug 24 '21 at 21:19
  • @ccpizza `includes` searches for the specified value; you wouldn’t want to create separate functions for each value; but you should be able to search for function objects as well. – Sebastian Simon Aug 24 '21 at 21:21
  • ``Array#includes`` uses the ``sameValueZero`` algorithm to determine whether an element is found. You can read more about it. ``Array#some`` tests whether at least one element in the array passes the test implemented by the provided function – Majed Badawi Aug 24 '21 at 21:28