Shifting certain elements to the end of array JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers as the first argument and a single number as the second argument.

Our function should check for all the instances of second number in the array, if there exists any, the function should push all those instances to the end of the array.

If the input array is −

const arr = [1, 5, 6, 6, 5, 3, 3];

And the second argument is 6

Then the array should become −

const output = [1, 5, 5, 3, 3, 6, 6];

Example

const arr = [1, 5, 6, 6, 5, 3, 3];
const num = 6;
const shiftElement = (arr, num) => {
   if (arr.length === 0){
      return arr
   };
   let index = 0; for(let e of arr){
      if(e !== num){
         arr[index] = e; index += 1;
      };
   }
   for (; index < arr.length; index++){
      arr[index] = num;
   };
};
shiftElement(arr, num);
console.log(arr);

Output

And the output in the console will be −

[
1, 5, 5, 3,
3, 6, 6
]
raja
Published on 21-Nov-2020 05:58:06
Advertisements