Ecco una funzione di incrocio sulla base di Array.prototype.filter
function intersect(a, b) {
var t;
if (b.length > a.length) t = b, b = a, a = t; // indexOf to loop over shorter
return a.filter(function (e) {
return b.indexOf(e) > -1;
});
}
var arr1 = ["mike", "sue", "tom", "kathy", "henry"];
arr2 = ["howey", "jim", "sue", "jennifer", "kathy", "hank", "alex"];
intersect(arr1, arr2); // ["sue", "kathy"]
Si potrebbe anche prendere in considerazione la seguente
var arr1 = ['sue', 'sue', 'kathy'],
arr2 = ['kathy', 'kathy', 'sue'];
È possibile che questo sarebbe ora dare ["sue", "sue", "kathy"]
. Se non vuoi duplicati potresti fare un ulteriore filtro su questo. Questo standardizzerebbe anche i risultati. cioè
return a
.filter(/* .. */) // same as before
.filter(function (e, i, c) { // extra step to remove duplicates
return c.indexOf(e) === i;
});
Aggiungendo questo ora tornerà lo stesso risultato come array precedenti (["sue", "kathy"]
), anche se c'erano duplicati.
fonte
2013-04-26 01:24:59
Vuoi che Sue e Kathy siano nei tuoi risultati in questo caso? – ggbranch
Sto cercando di trovare le partite, corretto. – Justin