w3resource

JavaScript: Remove specified elements from the right of a given array of elements

JavaScript fundamental (ES6 Syntax): Exercise-19 with Solution

Remove Right Elements from Array

Write a JavaScript program to remove specified elements from the right of a given array of elements.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
// Define a function called `remove_from_right` that removes elements from the right side of an array.
function remove_from_right(arr, n = -1){
  return arr.slice(n); // Slice the array from index n to the end, where n defaults to -1
}

// Example usage
console.log(remove_from_right([1, 2, 3])); // [3]
console.log(remove_from_right([1, 2, 3], -1)); // [3]
console.log(remove_from_right([1, 2, 3], -2)); // [2, 3]
console.log(remove_from_right([1, 2, 3], -4)); // [1, 2, 3]

Output:

[3]
[3]
[2,3]
[1,2,3]

Visual Presentation:

JavaScript Fundamental: Remove specified elements from the right of a given array of elements

Flowchart:

flowchart: Remove specified elements from the right of a given array of elements

Live Demo:

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


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that removes elements from the end of an array until a specified condition becomes true.
  • Write a JavaScript function that pops elements off an array while a predicate function returns false.
  • Write a JavaScript program that returns the truncated array after removing trailing elements that meet a condition.

Go to:


PREV : Remove Left Elements from Array.
NEXT : Expand 3-Digit to 6-Digit Color Code.

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.