Languages
[Edit]
EN

JavaScript - get last n elements from array excluding first element

0 points
Created by:
Niac
508

In this article, we would like to show you how to get the last n elements from the array excluding the first element in JavaScript.

Practical example

To get the last n elements from the array excluding the first element, we use slice() method with the second argument set to 1.

The Math.max() method is used to get all elements if the array.length is less than the number of elements that we want to get.

// ONLINE-RUNNER:browser;

const array = ['a', 'b', 'c', 'd', 'e'];
const n = 3;

const result = array.slice(Math.max(array.length - n, 1));

console.log(result);  // [ 'c', 'd', 'e' ]

See also

  1. JavaScript - get last n elements of array

References

  1. Array.prototype.length - JavaScript | MDN
  2. Array.prototype.slice() - JavaScript | MDN

Alternative titles

  1. JavaScript - get last n elements of array excluding first element
  2. JavaScript - get last n elements from array omitting first element
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join