0

I have an array:

    var arr = [1,2,4,5,1,2,3,4,5];

And I have another array:

    var removeArr = [1,3,5];

I want it to remove elements in arr that has in the removeArr:

    var result = arr.filter(function(item){
                 return item != removeArr[???];
                 });

I have tried to iterate it using loop but it doesn't work.

3

5 Answers 5

2

You can reach the desired output using Array#filter aswell as Array#indexOf functions.

var arr = [1,2,4,5,1,2,3,4,5],
    removeArr = [1,3,5],
    result = arr.filter(function(item){
      return removeArr.indexOf(item) == -1;
    });
    
    console.log(result);

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

Comments

2

 var arr = [1,2,4,5,1,2,3,4,5];
 
 var removeArr = [1,3,5];
 
 var result = arr.filter(x => !removeArr.includes(x));
 
 console.log(result);

Comments

2

You could use a Set and test against while filtering.

var array = [1, 2, 4, 5, 1, 2, 3, 4, 5],
    removeArray = [1, 3, 5],
    result = array.filter((s => a => !s.has(a))(new Set(removeArray)));
    
console.log(result);

3 Comments

This is a clever one! Took some time to understand how it works, thanks for it.
it uses a closure over a set.
Yes, I figured it out after rewriting into regular IIFE template.
1
var result = arr.filter(function(item){
    return removeArr.indexOf(item) === -1; // if the item is not included in removeArr, then return true (include it in the result array)
});

Comments

1

You can check if a value is in an array by checking if the index of the item is not -1.

var result = arr.filter(item => removeArr.indexOf(item) === -1)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.