[SOLVED] Dealing with multiple optional arguments in a javascript function

Issue

first time posting, basically doing the Odin project Exercise 04 – removeFromArray excercise:

https://github.com/TheOdinProject/javascript-exercises/tree/main/04_removeFromArray

I have got the first test to pass, however, i have no idea on how to write the program to deal with multiple optional arguments. I know i need to use the …arg, but do not really understand how to start or what to do, or the general construction of the function, please can someone help me to understand how to go about this? Below is a very poor attempt by me which doesnt work (not even sure if my logic is correct to get the desired output):

const removeFromArray = function (array1, ...args) {

    if (args == 3) {
        array1.splice(2, 1);
        return array1;
    } else if (args == 3 || args == 2) {
        array1.splice(2, 1);
        return array1.splice(1,1);
    }
};


console.log(removeFromArray([1, 2, 3, 4], 3, 2));

any help or advice on how to do this would be greatly appreciated.Thanks!

Solution

args is an array of arguments. So you just need to filter the original array and filter out those elements that are in array args:

function removeFromArray(array, ...args) {
    return array.filter(x => !args.includes(x))
};


console.log(removeFromArray([1, 2, 3, 4], 3, 2));

gives you:

[1, 4]

Answered By – re-za

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.