
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- How to add new array elements at the beginning of an array in JavaScript?
- How to move all capital letters to the beginning of the string in JavaScript?
- How to find elements of JavaScript array by multiple values?
- Move different elements to another array in MongoDB?
- How to duplicate elements of an array in the same array with JavaScript?
- How to replace elements in array with elements of another array in JavaScript?
- Map multiple properties in array of objects to the same array JavaScript
- How to calculate the XOR of array elements using JavaScript?
- Sort the second array according to the elements of the first array in JavaScript
- How to push an element at the beginning of an array in TypeScript?
- How to create permutation of array with the given number of elements in JavaScript
- How to find the sum of all elements of a given array in JavaScript?
- Shifting certain elements to the end of array JavaScript
- How to swap two array elements in JavaScript?
- Beginning and end pairs in array - JavaScript

Advertisements