JavaScript: Get the last element of an array
JavaScript Array: Exercise-4 with Solution
Write a JavaScript function to get the last element of an array. Passing the parameter 'n' will return the last 'n' elements of the array.
Test Data :
console.log(last([7, 9, 0, -2]));
console.log(last([7, 9, 0, -2],3));
console.log(last([7, 9, 0, -2],6));
Visual Presentation:
Sample Solution:
JavaScript Code:
// Function to get the last n elements of an array
var last = function(array, n) {
// Check if the input array is null, return undefined if true
if (array == null)
return void 0;
// Check if the value of n is null, return the last element of the array if true
if (n == null)
return array[array.length - 1];
// Use the slice method to get the last n elements of the array
// Math.max is used to ensure the starting index is not negative
return array.slice(Math.max(array.length - n, 0));
};
// Testing the function with various cases
console.log(last([7, 9, 0, -2]));
console.log(last([7, 9, 0, -2], 3));
console.log(last([7, 9, 0, -2], 6));
Output:
-2 [9,0,-2] [7,9,0,-2]
Flowchart:
ES6 Version:
// Function to get the last n elements of an array
const last = (array, n) => {
// Check if the input array is null, return undefined if true
if (array == null)
return undefined;
// Check if the value of n is null, return the last element of the array if true
if (n == null)
return array[array.length - 1];
// Use the slice method to get the last n elements of the array
// Math.max is used to ensure the starting index is not negative
return array.slice(Math.max(array.length - n, 0));
};
// Testing the function with various cases
console.log(last([7, 9, 0, -2]));
console.log(last([7, 9, 0, -2], 3));
console.log(last([7, 9, 0, -2], 6));
Live Demo:
See the Pen JavaScript - Get the last element of an array- array-ex-4 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to get the first element of an array. Passing a parameter 'n' will return the first 'n' elements of the array.
Next: Write a simple JavaScript program to join all elements of the following array into a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/javascript-array-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics