w3resource

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

JavaScript: Exercise-131 with Solution

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.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to remove n elements from the end of an given array.
Next: Write a JavaScript program to get the symmetric difference between two given arrays, using a provided function as a comparator.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-131.php