4

So I have one array:

var array1 = ['one', 'two', 'three', 'four', 'five']

And another:

var array2 = ['two, 'four']

How can I remove all the strings from array2 out of array1?

1

4 Answers 4

4

Just use Array#filter() and Array#indexOf() with bitwise not ~ operator for checking.

~ is a bitwise not operator. It is perfect for use with indexOf(), because indexOf returns if found the index 0 ... n and if not -1:

value  ~value   boolean
-1  =>   0  =>  false
 0  =>  -1  =>  true
 1  =>  -2  =>  true
 2  =>  -3  =>  true
 and so on 

var array1 = ['one', 'two', 'three', 'four', 'five'],
    array2 = ['two', 'four'];

array1 = array1.filter(function (a) {
    return !~array2.indexOf(a);
});

document.write("<pre>" + JSON.stringify(array1, 0, 4) + "</pre>");

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

2 Comments

And what about !~ ?
@RayonDabre bitwise negation operator, making code quite unreadable imho
2

Try this.

array2.forEach(item => array1.splice(array1.indexOf(item),1));

Comments

0

in jquery with inArray method:

for(array1)
  var idx = $.inArray(array1[i], array2);
  if (idx != -1) {//-1 not exists 
     array2.splice(idx, 1);
  } 

}

Comments

0

var array1 = ['one', 'two', 'three', 'four', 'five']
var array2 = ['two', 'four']
    
array1 = array1.filter(function(item){
   return array2.indexOf(item) === -1
})
// ['one', 'three', 'four', 'five']

document.write(array1)

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.