Search code examples
javascriptarraysloopsreturnreturn-type

How do I use return in a function?


I have the following code:

const removeFromArray = function (xArray, xNumber) {
    
    for(let i = 0; i < xArray.length; i++) {
        if(xArray[i] === xNumber) {
            const index = xArray.indexOf(xNumber);
            const x = xArray.splice(index, 0);
        } else {
           console.log(xArray[i]);
        }
    }
};

removeFromArray([1, 11, 3, 4], 11);

The function takes 2 arguments, the array and the element that you want to delete from the array. In order to check if the function is working, we have to use console.log. I used it and it's working. Now I have to implement this in an exercise and I need to remove the console.log and use return instead.

I tried using return but it only returns the first number in the array, like so: return xArray[i];

So how can I return the whole array?

removeFromArray([1, 2, 3, 4], 3); // should remove 3 and return [1,2,4]

Solution

  • Use return xArray to return the entire array. Do this in the if block when you remove the element.

    You need to specify length 1 in the splice() call to remove the element.

    const removeFromArray = function (xArray, xNumber) {
        
        for(let i = 0; i < xArray.length; i++) {
            if(xArray[i] === xNumber) {
                const index = xArray.indexOf(xNumber);
                xArray.splice(index, 1);
                return xArray;
            }
        }
    };
    
    console.log(removeFromArray([1, 11, 3, 4], 11));