w3resource

JavaScript: Move the specified amount of elements to the end of the array

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

Write a JavaScript program to move the specified amount of elements to the end of the array.

  • Use Array.prototype.slice() twice to get the elements after the specified index and the elements before that.
  • Use the spread operator (...) to combine the two into one array.
  • If offset is negative, the elements will be moved from end to start.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2
// Define the 'offset' function to offset the elements of an array by a specified amount.
const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];

// Offset the elements of the array by 2 positions to the right.
console.log(offset([1, 2, 3, 4, 5], 2)); // Output: [3, 4, 5, 1, 2]

// Offset the elements of the array by 2 positions to the left.
console.log(offset([1, 2, 3, 4, 5], -2)); // Output: [4, 5, 1, 2, 3]

Output:

[3,4,5,1,2]
[4,5,1,2,3]

Visual Presentation:

JavaScript Fundamental: Move the specified amount of elements to the end of the array

Flowchart:

flowchart: Move the specified amount of elements to the end of the array

Live Demo:

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


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to remove an event listener from an element.
Next: Write a JavaScript program to add an event listener to an element with the ability to use event delegation.

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.