How to move multiple elements to the beginning of the array in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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' ]
raja
Published on 24-Aug-2020 09:26:31
Advertisements