dtburgess
dtburgess

Reputation: 613

javascript: remove values from an array that are in a second array

Using pure javascript, starting with an array, I would like to return and array by removing values that match any value in a second array.

I have solved this problem, but I believe with more code than is really necessary.

I am hoping for a more concise or elegant solution using only javascript.

function removeValues(arr){
    array = arguments[0];
    args = Array.prototype.slice.call(arguments);
    len = arguments.length;
        filtered = array.filter(function(n){
            x = true;
            for (var i = 1; i < len; i++) {
                if (n == args[i]) { x = false; }
            }
            return x;
        });
    return filtered;
}

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

Should use a function that removes values from the first argument (an array) using values in one or more additional arguments.

Upvotes: 1

Views: 162

Answers (3)

When you're working with the filter function is not necessary to use loops because you're already in a loop. After converting the arguments into an array with [].slice.call(arguments), you could use indexOf that is responsible for returning the position of a value in an array, if a value is not exists, this returns -1, so we will take all the results that are -1

Your code could be reduced as well:

function removeValues(arr){
  return arr.filter(function(val){
    return [].slice.call(removeValues.arguments).slice(1).indexOf(val) === -1
  })
}

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


ES6 Method: Using Rest parameters and Arrow Functions

enter image description here

var removeValues = (arr, ...values) => arr.filter(val => values.indexOf(val) === -1)

Upvotes: 3

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Try this instead...

function removeValues(){
    var args = Array.prototype.slice.call(arguments).slice(1);
    return arguments[0].filter(function(value) {
        return args.indexOf(value) === -1;
    });
}

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

It does the exact same thing, but tidies it slightly.

Upvotes: 3

DDan
DDan

Reputation: 8276

Try like this:

var array1 = [ 1, 2, 3, 4, 5 ];
var array2 = [ 2, 3 ];

var result = array1.filter( function ( elem ) {
    return array2.indexOf( elem ) === -1;
});

See example: Running code

Upvotes: 1

Related Questions