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
How to move multiple elements to the beginning of the array in JavaScript?
In JavaScript, you can move multiple elements to the beginning of an array by identifying their positions and using array methods like splice() and unshift(). This technique is useful when you need to prioritize certain elements while maintaining the relative order of others.
Problem Overview
We need to create a function that takes an array and any number of strings as arguments. The function should check if these strings exist in the array and move them to the front while preserving their relative order.
Using splice() and unshift() Method
This approach removes elements from their current positions and adds them to the beginning of the array:
const arr = ['The', 'weather', 'today', 'is', 'a', 'bit', 'windy.'];
const pushFront = (arr, ...strings) => {
strings.forEach(el => {
const index = arr.indexOf(el);
if(index !== -1){
arr.unshift(arr.splice(index, 1)[0]);
}
});
};
pushFront(arr, 'today', 'air', 'bit', 'windy.', 'rain');
console.log(arr);
[ 'windy.', 'bit', 'today', 'The', 'weather', 'is', 'a' ]
Using Filter and Concat Method
An alternative approach that creates a new array instead of modifying the original:
const arr2 = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const moveToFront = (arr, ...elements) => {
const toMove = arr.filter(item => elements.includes(item));
const remaining = arr.filter(item => !elements.includes(item));
return [...toMove, ...remaining];
};
const result = moveToFront(arr2, 'date', 'apple', 'grape');
console.log(result);
console.log('Original array:', arr2);
[ 'apple', 'date', 'banana', 'cherry', 'elderberry' ] Original array: [ 'apple', 'banana', 'cherry', 'date', 'elderberry' ]
Preserving Element Order
To maintain the order of elements as specified in the arguments:
const arr3 = ['red', 'green', 'blue', 'yellow', 'purple'];
const moveToFrontOrdered = (arr, ...elements) => {
const found = elements.filter(el => arr.includes(el));
const remaining = arr.filter(item => !elements.includes(item));
return [...found, ...remaining];
};
const orderedResult = moveToFrontOrdered(arr3, 'yellow', 'red', 'orange');
console.log(orderedResult);
[ 'yellow', 'red', 'green', 'blue', 'purple' ]
Comparison
| Method | Modifies Original | Preserves Order | Performance |
|---|---|---|---|
| splice() + unshift() | Yes | Reverse order | Good for small arrays |
| filter() + concat() | No | Original order | Creates new array |
| Ordered approach | No | Argument order | Most flexible |
Conclusion
Moving multiple elements to the beginning of an array can be achieved through various methods. Choose splice() and unshift() for in-place modification, or use filter() methods for immutable operations that preserve element ordering.
