2016-04-07 8 views
4

So habe ich ein Array:Verwenden Sie ein Array von Strings, um ein anderes Array zu spleißen?

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

Und ein anderer:

var array2 = ['two, 'four'] 

Wie kann ich entfernen alle Saiten aus array2 aus array1?

+0

Was haben Sie versucht? –

+1

Mögliches Duplikat von [Was ist der schnellste oder eleganteste Weg, einen Satzunterschied mit Javascript-Arrays zu berechnen?] (Http://stackoverflow.com/questions/1723168/what-is-the-fastest-or-most-elegant-) way-to-compute-a-set-difference-using-javasc) –

Antwort

4

Verwenden Sie einfach Array#filter() und Array#indexOf() mit bitwise not~ Operator für die Überprüfung.

~ ist ein bitwise not operator. Es ist perfekt für den Einsatz mit indexOf(), weil indexOf zurück, wenn der Index 0 ... n gefunden und wenn nicht -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>");

+0

Und was ist mit '! ~'? – Rayon

+1

@RayonDabre bitweisem Negationsoperator, macht Code ziemlich unlesbar imho –

2

Versuchen Sie dies.

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

in jquery mit InArray Methode:

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

}

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)