javascriptarrayscontainsequalitypredicate

How to supply an equals/hash function to JS Array.includes()?


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.


Solution

  • 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) );