Home > other >  is there a way where I can empty the array using shift function?
is there a way where I can empty the array using shift function?

Time:11-10

Here I am trying to empty an array using recursion by calling shift function, but anyhow I am getting an error please help.

let arr = [1,2,3,4];
function del(arr){
    if(arr.length === 0){
        return []
    }else {
        let result = arr.shift();
        return del(result)
    }
}
console.log(del(arr))
   TypeError: arr.shift is not a function

CodePudding user response:

You need to handover the array after shifting an item.

Array#shift returns/removes the item at index zero or undefined if the array is empty.

function del(arr) {
    if (arr.length === 0) return arr;
    arr.shift();
    return del(arr);
}

const arr = [1, 2, 3, 4];      // keep the variable/omit reassignment
                               // just to give proof

console.log(del(arr) === arr); // same object reference
console.log(arr);              // empty array

CodePudding user response:

If all you're trying to do is empty the array, you can do:

let arr = [1, 2, 3, 4];
arr.splice(0, arr.length);
console.log(arr);

CodePudding user response:

The docs say:

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

Instead of returning del(result), which will call del with the shifted element as argument, you should call del(arr).

let arr = [1,2,3,4];
function del(arr){
    if(arr.length === 0){
        return []
    }else {
        let result = arr.shift(); //not using result, so no need to declare that variable
        return del(arr)
    }
}
console.log(del(arr))

  • Related