Skip to content Skip to sidebar Skip to footer

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’ w

Solution 1:

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

Some links:

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

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

Solution 2:

Try using .slice method with a negative start index:

varElements = newArray(1,2,3,4,5,6,7,8);

var last4 = Elements.slice(-4)

console.log(last4)

Solution 3:

You can just reassign x to be the length of the array if x is greater than the size of the array. Now you will at most print the entire array and at least print x.

var x = document.getElementById("x").value;

if(x > Elements.length)  // add this
    x = Elements.length;

for(var i=Elements.length - x; i <=Elements.length-1; i++)
{
    document.getElementById("result").innerHTML += Elements[i] + " ";
}

Solution 4:

const count = 5;
var Elements = new Array(1,2,3,4,5,6,7,8);
var result = Elements.slice(count > Elements.length ? 0 : Elements.length - count,Elements.length)
console.log(result)

Solution 5:

You want to make sure i is within range of the array. Elements.length - x needs to be equal or superior to 0.

Like other said you can (should ?) use slice but since you seem to be practicing with for loops then you better stick with it.

varElements = newArray(1,2,3,4,5,6,7,8);

functionelements(){
    var x = document.getElementById("x").value;

    for(var i=Math.max(Elements.length - x, 0); i <=Elements.length-1; i++)
    {
        document.getElementById("result").innerHTML += Elements[i] + " ";
    }

}

Post a Comment for "I Want To Print The Last 'n' Elements Of An Array"