- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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' ]
Advertisements