I am writing a JavaScript function to get the last 'n' elements of the array. If array has 6 elements and if user gives 4, it has to return last 4 elements. If user gives ‘n’ which is greater than the number of elements in the array, then it should return all elements.
The problem is if If the array has 8 elements and I give number 10. The result is : undefined undefined 1 2 3 4 5 6 7 8
I want to display only the numbers without "undefined".
Thanks
HTML code
The array is :
1,2,3,4,5,6,7,8
<br>
x:
<input type="number" id="x" value="2" >
<br>
<button onclick="elements()"> Get the elements </button>
<p id="result"></p>
<script src="ex10.js"></script>
JavaScript code
var Elements = new Array(1,2,3,4,5,6,7,8);
function elements(){
var x = document.getElementById("x").value;
for(var i=Elements.length - x; i <=Elements.length-1; i++)
{
document.getElementById("result").innerHTML += Elements[i] + " ";
}
}
Method #2 : Using islice() + reversed() The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end.
In this program firstly take the array variable. the second step is to calculate the size of the array using sizeof the operator. size = sizeof(arr)/sizeof(int); then, the last step to print the arr [size - 1].
There is 2 indexing in Python that points to the last element in the list. list[ len – 1 ] : This statement returns the last index if the list. list[-1] : Negative indexing starts from the end.
To get the last item in an array when you don't know the length of that array: const lastItem = animals[animals. length - 1] ; The lastItem variable now holds the value of horse.
You could take slice
with a negative count from the end. Then join
the elements for a formatted output.
Some links:
Array#slice
Array#join
var array = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(array.slice(-4).join(' '));
Try using .slice
method with a negative start index:
var Elements = new Array(1,2,3,4,5,6,7,8);
var last4 = Elements.slice(-4)
console.log(last4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With