dragi
dragi

Reputation: 1512

Removing elements from an array by value in Javascript

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!

Upvotes: 1

Views: 98

Answers (4)

Marcel T.
Marcel T.

Reputation: 126

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]

Upvotes: 0

nikksan
nikksan

Reputation: 3471

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

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

Upvotes: -1

Ele
Ele

Reputation: 33726

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

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386550

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

Upvotes: 4

Related Questions