Search code examples
javascriptarraysshift

Remove element from


I am trying to remove first element from an array without using any methods recursively. What is wrong in my code?


Solution

  • arr=[1,2,3,4];
    function rem(arr){
    let res=[];
    if(!this.index)  // optional if index is maintaining in outside
        this.index = 0; // optional, this would get created as a global variable & make sure that you haven't use this variable in somewhere else.
    if(arr.length>1){
        if (this.index<arr.length-1){
            arr[this.index]=arr[this.index+1];
            this.index++;
            return rem(arr);
        }
        else{
            this.index = undefined; // optional, make it to initial state
            arr.length--;
            return arr;
        }
     }
     this.index = undefined; // optional, make it to initial state
     return res;
     }