6

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

7 Answers 7

13

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(' '));

Sign up to request clarification or add additional context in comments.

Comments

10

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)

Comments

1

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

Comments

1

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)

Comments

1

There are other ways to achieve why you need, for example by using .slice(), .map() etc.

If you need to stick to for loops, thn Math.min() can come handy:

const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const elX = document.getElementById("x"); const elR = document.getElementById("result"); function elements() { const x = parseInt(elX.value, 10); // use parseInt with radix! const min = Math.min(arr.length, x); let html = ""; for (var i = arr.length - min; i <= arr.length - 1; i++) { html += arr[i] + " "; } elR.innerHTML = html; // Insert into DOM only once! }
x: <input type="number" id="x" value="2"> <button onclick="elements()">Get the last N elements</button> <p id="result"></p>

Here's the example using .slice() and .map()

const arr = [1, 2, 3, 4, 5, 6, 7, 8]; const elX = document.getElementById("x"); const elR = document.getElementById("result"); function elements() { const x = parseInt(elX.value, 10); elR.innerHTML = arr.slice(-x).map(n => `Item:${n}`).join('<br>'); }
x: <input type="number" id="x" value="2"> <button onclick="elements()">Get the last N elements</button> <p id="result"></p>

4 Comments

"thn Math.min() can come handy" - Why?
I'm aware of why you're using it. But TO is obviously a beginner, and yet nobody tries to explain their solutions, or the problems with the code from TO, or ...
well .. i did : (answer below) "You want to make sure i is within range of the array. Elements.length - x needs to be equal or superior to 0."
@Andreas thx yes. Usually I review my own answers when done with the general picture, but glad to have another pair of eyes °.0
1
const drivers = ['Sally', 'Bob', 'Freddy', 'Claudia']; function returnFirstTwoDrivers(drivers) { return drivers.slice(0,2) } function returnLastTwoDrivers(drivers) { return drivers.slice(-2) } document.getElementById("mocha").innerHTML = 'ARRAY 1: ' + returnFirstTwoDrivers(drivers) + '<br/>ARRAY 2: ' + returnLastTwoDrivers(drivers); 

Code Output

1 Comment

When adding an answer to an older question with many existing answers, it is important to add an explanation of how yours differs from others, or you may get downvotes. For instance, this answer uses slice, as do several other existing answers, including the most upvoted. Also, the answer uses an example array that is different than the original question's, which makes it harder for the curious to compare to other answers.
0

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.

var Elements = new Array(1,2,3,4,5,6,7,8); function elements(){ 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] + " "; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.