- 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
How to move multiple elements to the beginning of the array in JavaScript?
We have to write a function that takes an array and any number of strings as arguments. The task is to check if the strings occur within the array. If it does, we have to move that particular to the front of the array.
Therefore, let’s write the code for this function −
Example
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);
Output
The output in the console will be −
[ 'windy.', 'bit', 'today', 'The', 'weather', 'is', 'a' ]
Advertisements