Last N Elements

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the lastN function which is used to extract the last n elements of an array. We will learn how to use the Array.prototype.slice() method to achieve this and see how it can be implemented in our JavaScript programs. By the end of this lab, you will have a better understanding of how to manipulate arrays in JavaScript and extract specific elements from them.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28466{{"`Last N Elements`"}} javascript/data_types -.-> lab-28466{{"`Last N Elements`"}} javascript/arith_ops -.-> lab-28466{{"`Last N Elements`"}} javascript/comp_ops -.-> lab-28466{{"`Last N Elements`"}} end

How to Get Last N Elements of an Array in JavaScript

To get the last n elements of an array in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.

  2. Use Array.prototype.slice() with a start value of -n to get the last n elements of the array.

Here's the JavaScript code to get the last n elements of an array:

const lastN = (arr, n) => arr.slice(-n);

To test the code, call the lastN() function with the array and the number of elements you want to get, like this:

lastN(["a", "b", "c", "d"], 2); // ['c', 'd']

Summary

Congratulations! You have completed the Last N Elements lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like