Ecco un'implementazione di lavoro utilizzando Vanilla JS:
function haveMatchingElements(firstArray, secondArray) {
var stringsInFirstArray = parse(firstArray, 'string'),
stringsInSecondArray = parse(secondArray, 'string'),
numbersInFirstArray = parse(firstArray, 'number'),
numbersInSecondArray = parse(secondArray, 'number'),
stringResults = compare(stringsInFirstArray, stringsInSecondArray),
numberResults = compare(numbersInFirstArray, numbersInSecondArray);
if (stringResults && numberResults) {
return true;
} return false;
function parse(array, type) {
var arr = [];
arr = array.sort().filter(function(index) {
if (typeof index == type)
return index;
});
return arr;
}
function compare(firstArray, secondArray) {
if (firstArray.length !== secondArray.length)
return false;
for (var i = firstArray.length; i--;) {
if (firstArray[i] !== secondArray[i])
return false;
}
return true;
}
}
Questo analizza delle corde di un numero in diverse matrici e li controlla separatamente. Ciò correggerà il problema di 1
e "1"
corrispondente a true
a causa della conversione implicita del tipo causata dalla funzione sort
.
L'implementazione è semplice:
var arr1 = ['1', 1];
var arr2 = [1, '1'];
var results = haveMatchingElements(arr1, arr2);
console.log(results); // true
tutti gli elementi sono unici nella matrice ?? – Pratik
@Pratik No, confrontando i due array. – Scimonster
Sì per il mio caso, ma sarebbe meglio se potesse gestire anche elementi duplicati. – cytsunny