Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to print the last 'n' elements of an array

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] + " ";
    }

}
like image 691
Andreia Malinici Avatar asked Jan 21 '19 15:01

Andreia Malinici


People also ask

How do I get the last 10 elements of a list in Python?

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.

How do I print the last element of an array in C?

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].

How do you print the last value in an array in Python?

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.

How do you find the last object of an array?

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.


2 Answers

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(' '));
like image 60
Nina Scholz Avatar answered Nov 09 '22 10:11

Nina Scholz


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)
like image 43
Kosh Avatar answered Nov 09 '22 11:11

Kosh