1

It's a bit fuzzy for me, but I'm trying to create a simple function that takes an array and some arguments and removes the arguments from the array.

For example if I have an array such as [1,2,3,4] and the arguments 2,3 it would return [1,4] as a result.

This is what I have so far:

const removeFromArray = (arr) => {
    let args = Array.from(arguments);

    return arr.filter(function (item) {
        !args.includes(item);
    });
}

It doesn't work though. It works if I want to remove all the items from the array, but doesn't if I only go for specific ones.

How can I make this work so that it works even if I'm supplying an argument that is not part of the array (I want it to ignore those) and also if I have strings in the array as well?

Thanks in advance!

1
  • 2
    please add the call of the function as well. Commented Oct 20, 2018 at 15:25

4 Answers 4

4

You could take rest parameters ... for the items to exclude the values.

const removeFromArray = (array, ...items) => array.filter(item => !items.includes(item));

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

To use you style, you need to exclude the first item of arguments, because this is the array with all items.

let args = Array.from(arguments).slice(1);
//                              ^^^^^^^^^
Sign up to request clarification or add additional context in comments.

Comments

2

In arrow functions the implicit object arguments doesn't exist, so declare the function using the keyword function, likewise, you need to return the result of the function includes within the handler of the function filter.

const removeFromArray = function() {
    let [arr, ...args] = Array.from(arguments);
    return arr.filter(function (item) {
        return !args.includes(item);
    });
}

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

Comments

0

Add a second parameter for the items you want to have removed.

const removeFromArray = (arr, toBeRemoved) => {
    return arr.filter(item => !toBeRemoved.includes(item));
}

Example call:

const array = [1, 2, 3, 4]
const newArray = removeFromArray(arr, [2, 3])
console.log(newArray) // [1, 4]

Comments

-1

Stick it to the Array.prototype, might use it somewhere else

Array.prototype.remove = function(...args) {
  return this.filter(v => !args.includes(v));
}

Comments

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.