Good morning! Here's your coding interview problem for today.
This problem was asked by Apple.
Please implement your own Array.prototype.findLast()
Example
Array.prototype.findEndIdx = function (val) {
}
let arr = [1, 2, 2, 4];
console.log(arr.findEndIdx(2)); // 2
Note: Do not use native Array.prototype.findLast() in your code
Solution
if (!Array.prototype.findLastIndex) {
Array.prototype.findLastIndex = function (value) {
for (let i = this.length - 1; i >= 0; i--) {
if (this[i] === value) {
return i;
}
}
return -1;
};
}
Explanation
- Loop backwards from end of array to start
- Check if current element matches value
- If so, return current index
- If loop completes, value not found so return -1
Top comments (0)