6

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!

2 Answers 2

7

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that works perfectly, and makes sense now to me!
1

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));

1 Comment

Thank you I now understanding the logic needed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.