
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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' ]
- Related Questions & Answers
- How to move all capital letters to the beginning of the string in JavaScript?
- How to add new array elements at the beginning of an array in JavaScript?
- How to find elements of JavaScript array by multiple values?
- Move different elements to another array in MongoDB?
- Map multiple properties in array of objects to the same array JavaScript
- Sort the second array according to the elements of the first array in JavaScript
- How to duplicate elements of an array in the same array with JavaScript?
- How to move all the zeros to the end of the array from the given array of integer numbers using C#?
- Shifting certain elements to the end of array JavaScript
- How to replace elements in array with elements of another array in JavaScript?
- How to create permutation of array with the given number of elements in JavaScript
- PHP program to add item at the beginning of associative array
- Grouping array of array on the basis of elements in JavaScript
- How to find the mean of corresponding elements of multiple matrices in R?
- C# Program to return specified number of elements from the beginning of a sequence
Advertisements