Similar Problems

Similar Problems not available

Array Prototype Last - Leetcode Solution

Companies:

LeetCode:  Array Prototype Last Leetcode Solution

Difficulty: Unknown

Topics: unknown  

The problem, Array Prototype Last, on LeetCode asks us to implement the last function on the array prototype by extending it to take an optional parameter n that specifies the number of elements to return from the end of the array.

The problem can be solved using the slice method of the array. The slice method returns a new array with the specified range of elements from the original array. The range of elements is specified by two indices, the start index, and the end index.

To get the last n elements from the array, we need to calculate the start index and end index for the slice method. The end index will be the length of the array, and the start index will be the length of the array minus n. If the number of elements to return (n) is not specified, we need to return the last element of the array.

The solution for the problem is:

Array.prototype.last = function(n) {
  // if n is not specified, return the last element of the array
  if (n == undefined || n == 1) {
    return this[this.length - 1];
  }
  
  // if n is greater than the length of the array, return the entire array
  if (n > this.length) {
    return this.slice(0);
  }

  // calculate the start and end index for the slice method
  var startIndex = this.length - n;
  var endIndex = this.length;
  
  // return the last n elements of the array
  return this.slice(startIndex, endIndex);
};

The last function takes an optional parameter n that specifies the number of elements to return. If n is not specified or n is 1, it returns the last element of the array. If n is greater than the length of the array, it returns the entire array. Otherwise, it calculates the start and end index for the slice method and returns the last n elements of the array.

Array Prototype Last Solution Code

1