[Easy] Implement Array.prototype.at
March 6, 2024
Question Prompt
Implement Array.prototype.at
, a function that accepts an integer as input and retrieves the corresponding item at that index within an array? It should accommodate both positive and negative integers, with negative integers indicating counting from the end of the array.
const arr = ["Explain", "This"];
arr.myAt(0); // Explain
arr.myAt(1); // This
arr.myAt(2); // undefined
arr.myAt(-1); // This
arr.myAt(-2); // Explain
arr.myAt(-3); // undefined
Solutions
Looking to practice more questions like these? We recommend GreatFrontEnd, the best platform for honing your frontend interview skills!
First, create a function that takes an index
parameter, representing the index of the array element we want to retrieve.
The crucial concept here is to normalize the index, ensuring it works correctly for both positive and negative values. actualIndex
is calculated using a ternary operator. If the provided index is non-negative (index >= 0
), it is used directly. If the index is negative, it is adjusted by adding the length of the array (index + this.length
), effectively counting from the end of the array.
After doing the normalization, we can then return the element at the calculated actualIndex
in the array.
Array.prototype.at = function (index) {
const actualIndex = index >= 0 ? index : index + this.length;
return this[actualIndex];
};