Skip to the solution
EasyDSAAsked in 20246 min read

Polyfill Array.prototype.findLast() and findLastIndex()

3.7k views

The problem

Problem, as an interviewer would state it: "Implement Array.prototype.myFindLast and myFindLastIndex — like find/findIndex, but searching from the END of the array toward the START, returning the LAST matching element."

Examples:

Code
[5, 12, 8, 130, 44].myFindLast(n => n > 10); // 44 -- the LAST element greater than 10

Clarifying questions expected:

  • What is the real, correct "no match found" return value for each — matching find()'s own undefined, and findIndex()'s own -1, respectively?
  • Does this genuinely need to search from the end for efficiency, or would reversing the array first and using find() be equally correct?
  • Should real sparse-array holes be handled the same way as find()'s own real, documented behavior (which does NOT skip holes, unlike map/filter)?

Code / implementation expected: Yes — real, direct proof against the ACTUAL native findLast/findLastIndex, confirming identical output including the correct "no match" conventions.

  • array

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: findLast()/findLastIndex() match the real native methods exactly, including the correct no-match conventions

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 1 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Pub-Sub topic structures

Continue