Remove number from array and shift the remaining ones 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 number as the second argument.

The function should, if the number specified by second argument exists in the array, remove it and shift all the elements right to it one place left. The only condition is that we cannot use the Array methods like slice(), splice and others.

If there exists more than one instances of the number in the array, we should remove the first one.

For example −

If the input array is −

const arr = [3, 5, 6, 3, 7, 8, 8, 6];
const num = 7;

Then the array should become −

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

Example

const arr = [3, 5, 6, 3, 7, 8, 8, 6]; const num = 7;
const removeElement = (arr = [], num) => {
   let index = arr.indexOf(num);
   if(index === -1){
      return;
   };
   while(index + 1 < arr.length){
      arr[index] = arr[index + 1];
      arr[index + 1] = arr[index] - arr[index + 1];
      arr[index] = arr[index] - arr[index + 1]; ++index;
   };
   arr.pop();
};
removeElement(arr, num);
console.log(arr);

Output

And the output in the console will be −

[
3, 5, 6, 3,
8, 8, 6
]
raja
Published on 25-Nov-2020 07:41:37
Advertisements