0

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);
1
  • @nnnnnn No, it just returns the first argument. Commented Apr 14, 2016 at 5:36

2 Answers 2

1

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

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

Comments

1

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

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.