Home > Back-end >  Dealing with multiple optional arguments in a javascript function
Dealing with multiple optional arguments in a javascript function

Time:03-16

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!

CodePudding user response:

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]

CodePudding user response:

args is an array, so you can loop it via forEach and remove items from your array1

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

  args.forEach((arg) => {
    const index = array1.indexOf(arg);
    if (index > -1)
      array1.splice(index, 1);
  });
  return array1;
    
};


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

  • Related