- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ]
- Related Articles
- Shift certain array elements to front of array - JavaScript
- How to create permutation of array with the given number of elements in JavaScript
- How to count the number of elements in an array below/above a given number (JavaScript)
- JavaScript Array shift()
- Move last element to front of a given Linked List in C++
- Array shift() in JavaScript
- Golang Program To Get The Last Given Number Of Items From The Array
- C++ Program to get the last given number of items from the array
- Swift Program to get the last given number of items from the array
- Swift Program to remove the last given number of items from the array
- Shift the bits of integer array elements to the left in Numpy
- Shift the bits of integer array elements to the right in Numpy
- Shift the bits of array elements of a Two-Dimensional array to the left in Numpy
- Shift the bits of array elements of a Two-Dimensional array to the right in Numpy
- Remove number from array and shift the remaining ones JavaScript

Advertisements