1

I've tried this

function removeFromArray(manyMoreArgs, number) {
  let i = 0;
  while (i < manyMoreArgs.length) {
    if (manyMoreArgs[i] === number) {
      manyMoreArgs.splice(i, 1);
    } else {
      i++;
    }
  }
  return manyMoreArgs;
}
console.log(removeFromArray([1, 2, 3, 4], 3)); // result = [1, 2, 4] this removes 3 from array. it works! but then >>
console.log(removeFromArray([1, 2, 3, 4], 3, 2)); // result = [1, 2, 4] this removes 3 from array too but I also want to remove 2 from array

What should I do if I want to remove numbers from array?

2 Answers 2

3

You could either define your numbers parameter as an array

function removeFromArray(manyMoreArgs, numbers) {
  let i = 0;
  while (i < manyMoreArgs.length) {
    if (numbers.includes(manyMoreArgs[i])) {
      manyMoreArgs.splice(i, 1);
    } else {
      i++;
    }
  }
  return manyMoreArgs;    
}

console.log(removeFromArray([1, 2, 3, 4], [3]));// result = [1, 2, 4] this removes 3 from array. it works! but then >>
console.log(removeFromArray([1, 2, 3, 4], [3, 2]));// result = [1, 2, 4] this removes 3 from array too but I also want to remove 2 from array

or as a variadic argument

function removeFromArray(manyMoreArgs, ...numbers) {
  let i = 0;
  while (i < manyMoreArgs.length) {
    if (numbers.includes(manyMoreArgs[i])) {
      manyMoreArgs.splice(i, 1);
    } else {
      i++;
    }
  }
  return manyMoreArgs;    
}

console.log(removeFromArray([1, 2, 3, 4], 3));// result = [1, 2, 4] this removes 3 from array. it works! but then >>
console.log(removeFromArray([1, 2, 3, 4], 3, 2));// result = [1, 2, 4] this removes 3 from array too but I also want to remove 2 from array

Sign up to request clarification or add additional context in comments.

6 Comments

oh big thanks, it works now! I have to take a look what .include is. (i'm a beginner, I've never seen this syntax before)
If it works, feel free to accept the answer ...
I click the ✔ it turns green then it turns back to grey again automatically did I miss something?
because you accepted another answer ...
|
1

I think you can make use of a JavaScript function that takes in these two arrays and filters the first to contain only those elements that are not present in the second array. And then return the filtered array.

    const removeNum = (arr,...numbers) =>{
       const arr2 = [...numbers]
       console.log(arr2); 
       numbers = arr.filter(el => {
          return arr2.indexOf(el) === -1;
        });;
       console.log(numbers);   
    }

removeNum([1, 2, 3, 4], 3, 2)

1 Comment

thank you, today I learn new things (.filter/.include) you gave me new perspective

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.