Shift last given number of elements to front of array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have to write an Array function, say prependN() that takes in a number n (n <= length of array the function is used with) and it takes n elements from the end and puts them in front of the array.

We have to do this in place and the function should only return a boolean based on the successful completion or failure of the task.

For example −

// if the input array is:
const arr = ["blue", "red", "green", "orange", "yellow", "magenta",
// and the number n is 3,
// then the array should be reshuffled like:
const output = ["yellow", "magenta", "cyan", "blue", "red", "green",
// and the return value of function should be true

Now, let’s write the code for this function −


const arr = ["blue", "red", "green", "orange", "yellow", "magenta",
Array.prototype.reshuffle = function(num){
const { length: len } = this;
   if(num > len){
      return false;
   const deleted = this.splice(len - num, num);
   return true;


The output in the console will be −

   'orange', 'yellow',
   'magenta', 'cyan',
   'blue', 'red',
Published on 28-Aug-2020 17:05:39