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' ]

Updated on: 24-Aug-2020

588 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements