Consider this alternative approach, where a compare function is included as an argument:
function findIndexInArray(ar, value, startIdx, comp) {
if (!comp) {
if (startIdx instanceof Function) {
comp = startIdx;
startIdx = 0;
}
else return ar.__origFindIndex(value, startIdx);
}
if (!startIdx) startIdx = 0;
for (var i=startIdx ; i < ar.length ; i++) {
if (comp(ar[i], value))
return i;
}
return -1;
}
// Preserve original findIndex method to maintain default functionality
Array.prototype.__origFindIndex = Array.prototype.findIndex;
// Modify the Array.findIndex to accommodate a custom comparison function.
Array.prototype.findIndex = function(value, startIndex, comp) {
return findIndexInArray(this, value, startIndex, comp);
}
You can utilize it in the following manner:
findIndexInArray(arr, {x:1, y:2}, function (a,b) {
return a.x == b.x && a.y == b.y;
});
arr.findIndex({x:1, y:2}, function (a,b) {
return a.x == b.x && a.y == b.y;
});
arr.findIndex({x:1, y:2}, 1, function (a,b) {
return a.x == b.x && a.y == b.y;
});
An advantage of this method is that it will fall back to the original findIndex if no custom comparison function is provided.
[1,2,3,4].findIndex(3);