w3resource

JavaScript: Get an array with n elements removed from the beginning from a given array

JavaScript: Exercise-131 with Solution

Remove n Elements from Beginning

Write a JavaScript program to get an array with n elements removed from the beginning from a given array.

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

Sample Solution:

JavaScript Code:

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

// Define the 'take' function.
const take = (arr, n = 1) => arr.slice(0, n);

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

Output:

[1,2,3]
[]

Visual Presentation:

JavaScript Fundamental: Get an array with n elements removed from the beginning from a given array.

Flowchart:

flowchart: Get an array with n elements removed from the beginning from a given array

Live Demo:

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


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that removes the first n elements from an array and returns the remaining elements.
  • Write a JavaScript function that uses the slice method to skip n elements at the start of an array.
  • Write a JavaScript program that validates the number of elements to remove and returns a new array without the first n items.

Go to:


PREV : Remove n Elements from End.
NEXT : Symmetric Difference with Comparator.

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.