w3resource

JavaScript: Remove n elements from the end of a given array

JavaScript fundamental (ES6 Syntax) exercises, practice and solution: Exercise-130 with Solution

Remove n Elements from End

Write a JavaScript program to remove n elements from the end of a given array.

  • Use Array.prototype.slice() to create a slice of the array with n elements taken from the end.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 

// Define the 'takeRight' function.
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);

// Test the 'takeRight' function.
console.log(takeRight([1, 2, 3], 2)); // Output: [2, 3]
console.log(takeRight([1, 2, 3])); // Output: [3]

Output:

[2,3]
[3]

Visual Presentation:

JavaScript Fundamental: Remove n elements from the end of a given array.

Flowchart:

flowchart: Remove n elements from the end of a given array

Live Demo:

See the Pen javascript-basic-exercise-130-1 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that removes the last n elements from an array and returns the modified array.
  • Write a JavaScript function that uses array slicing to drop n elements from the end of an array.
  • Write a JavaScript program that validates the value of n and then truncates the array accordingly.

Go to:


PREV : Remove Elements from End Until True.
NEXT : Remove n Elements from Beginning.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.