JavaScript get the last n elements of array | slice example code

How to get the last n elements of array in JavaScript?

For an example given array have 10 elements and we want the last 4 elements.

Use slice and length methods.

<html>  
<head>  
    <title>Sample Code</title>  
    <script type="text/javascript">  
  	var num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  	var arr = num.slice(Math.max(num.length - 4, 1))
	alert(arr)
    </script>  
</head>  
</html> 

Output:

JavaScript get the last n elements of array

You can also take slice with a negative count from the end. Then the elements for formatted output.

var array = [1, 2, 3, 4, 5, 6, 7, 8];

console.log(array.slice(-4).join(' '));

How to JavaScript get the last element of the array, es6?

You can access last element of an array in JS using an length method method.

var my_array = /* some array here */;
var last_element = my_array[my_array.length - 1];

Do comment if you have any questions and suggestions this topic.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.