Shift last given number of elements to front of array JavaScript



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", "cyan"]; // and the number n is 3, // then the array should be reshuffled like: const output = ["yellow", "magenta", "cyan", "blue", "red", "green", "orange"]; // and the return value of function should be true

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

Example

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

Output

The output in the console will be −

true [    'orange', 'yellow',    'magenta', 'cyan',    'blue', 'red',    'green' ]
Updated on: 2020-08-28T13:37:36+05:30

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements