Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Shift last given number of elements to front of array JavaScript
In JavaScript, moving elements from the end of an array to the front is a common array manipulation task. This tutorial shows how to create a function that shifts the last n elements to the beginning of an array in-place.
Problem Statement
We need to create an array method reshuffle() that:
- Takes a number n (where n ? array length)
- Moves the last n elements to the front
- Modifies the array in-place
- Returns true on success, false if n exceeds array length
Example Input and Output
// Original array const arr = ["blue", "red", "green", "orange", "yellow", "magenta", "cyan"]; // After reshuffle(3), last 3 elements move to front: // Result: ["yellow", "magenta", "cyan", "blue", "red", "green", "orange"]
Implementation
Here's how to implement the reshuffle() method using splice() and unshift():
const arr = ["blue", "red", "green", "orange", "yellow", "magenta", "cyan"];
Array.prototype.reshuffle = function(num) {
const { length: len } = this;
// Check if num exceeds array length
if (num > len) {
return false;
}
// Extract last 'num' elements
const deleted = this.splice(len - num, num);
// Add them to the front
this.unshift(...deleted);
return true;
};
console.log("Original array:", arr);
console.log("Reshuffle 4 elements:", arr.reshuffle(4));
console.log("Modified array:", arr);
Original array: [ 'blue', 'red', 'green', 'orange', 'yellow', 'magenta', 'cyan' ] Reshuffle 4 elements: true Modified array: [ 'orange', 'yellow', 'magenta', 'cyan', 'blue', 'red', 'green' ]
How It Works
-
Validation: Check if
numexceeds array length -
Extract:
splice(len - num, num)removes last n elements and returns them -
Prepend:
unshift(...deleted)adds extracted elements to the front - Return: Boolean indicating success/failure
Alternative Implementation
Using array slicing and concatenation:
Array.prototype.reshuffleAlternative = function(num) {
if (num > this.length) return false;
const lastElements = this.slice(-num);
const remainingElements = this.slice(0, -num);
// Clear array and rebuild
this.length = 0;
this.push(...lastElements, ...remainingElements);
return true;
};
const arr2 = ["a", "b", "c", "d", "e"];
console.log("Success:", arr2.reshuffleAlternative(2));
console.log("Result:", arr2);
Success: true Result: [ 'd', 'e', 'a', 'b', 'c' ]
Edge Cases
const testArray = [1, 2, 3];
// Test edge cases
console.log("Empty reshuffle:", testArray.reshuffle(0)); // Should work
console.log("Array after 0:", testArray);
console.log("Exceeds length:", testArray.reshuffle(5)); // Should fail
console.log("Array unchanged:", testArray);
Empty reshuffle: true Array after 0: [ 1, 2, 3 ] Exceeds length: false Array unchanged: [ 1, 2, 3 ]
Conclusion
The reshuffle() method efficiently moves array elements using splice() and unshift(). It handles edge cases and modifies arrays in-place while returning a success indicator.
Advertisements
