DEV Community

Cover image for Javascript polyfill implement Array.prototype.findLast()
chandra penugonda
chandra penugonda

Posted on • Edited on

Javascript polyfill implement Array.prototype.findLast()

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
Enter fullscreen mode Exit fullscreen mode

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;
  };
}

Enter fullscreen mode Exit fullscreen mode

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)