Jade Cowan
Jade Cowan

Reputation: 2583

Removing Values from an Array using the Filter Method

Given an array and subsequent unknown number of arguments, how can I remove all elements from the initial array that are of the same value as these arguments? This is what I have so far:

function destroyer(arr) {
    var arrayOfArgs = [];
    var newArray = [];
    for (var i = 0; i < arguments.length; i++) {
        newArray = arr.filter(function (value) {
            return value !== arguments[i + 1];
        });
    }
    return newArray;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Upvotes: 0

Views: 52

Answers (2)

Michał Perłakowski
Michał Perłakowski

Reputation: 92521

Use rest parameters to specify the subsequent arguments, Array.prototype.filter() with an arrow function to filter the arr, and Array.prototype.includes() to determine whether args contains specific item.

function destroyer(arr, ...args) {
  return arr.filter(x=> !args.includes(x))
}

console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3))

Upvotes: 1

Tushar
Tushar

Reputation: 87203

You can use Array#filter with arrow function Array#includes and rest parameters.

Demo

function destroyer(arr, ...remove) {
    return arr.filter(e => !remove.includes(e));
}

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

function destroyer(arr, ...remove) {
    return arr.filter(e => !remove.includes(e));
}

var updatedArr = destroyer([1, 2, 3, 1, 2, 3], 2, 3);
console.log(updatedArr);

Equivalent Code in ES5:

function destroyer(arr) {
    var toRemove = [].slice.call(arguments, 1);
    return arr.filter(function(e) {
        return toRemove.indexOf(e) === -1;
    });
}

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

function destroyer(arr) {
    var toRemove = [].slice.call(arguments, 1);
    return arr.filter(function (e) {
        return toRemove.indexOf(e) === -1;
    });
}

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

Upvotes: 1

Related Questions