I am pleased to learn if this can be optimized compared to the current method and tailored to your specific requirements.
Array.prototype.findKey = function(key, value, start = 0, revert = false, restart = true) {
let __forward = function(index, limit, array, key, value) {
let ele = null;
while (index < limit && (ele = array[index])[key] !== value) index++;
return {index: index, value: ele};
},
__backward =function(index, limit, array, key, value) {
let ele = null;
while (index > limit && (ele = array[index])[key] !== value) index--;
return {index: index, value: ele};
};
if (!(typeof key !== "string" || start < 0 || !(start < this.length) || typeof this[0] !== "object")) {
let length = this.length, result;
/* no revert: forward direction, until first match */
if (!revert) {
result = __forward(start, length, this, key, value);
if (result.index < length)
return result;
else if (restart && start > 0) {
result = __forward(0, start, this, key, value);
if (result.index < start)
return result;
}
} else {
/* revert: backward direction, until last match */
result = __backward(start, -1, this, key, value);
if (result.index > -1)
return result;
else if (restart && start < length-1) {
result = __backward(length-1, start, this, key, value, true);
if (result.index > start)
return result;
}
}
}
return {index: -1, value: null};
}
usage:
let a = [{id: 1, value: "rock"}, {id: 2, value: "roll"}, ...];
let item2 = a.findKey("id", 2, a.length-1, true),
val2 = item2.value,
idx2 = item2.index;
let item1 = a.findKey("id", 1, idx2 - 1, true),
val1 = item1.value,
idx1 = item1.index;
etc...
As a regular function:
window.OO7array_findKey = function(key, value, start = 0, revert = false, restart = true) {
/* same as above script, dont worry feel free to copy and paste here */
};