Una función para comparar dos matrices, para comprobar si ambas tienen los mismos elementos. Incluso si están fuera de servicio ...
Es bueno para arreglos simples. [Cadena, Número, Booleano, Nulo, NaN].
No uso .sort (), modifica la matriz original. Algunos dicen que es malo ...
Precaución. Esta función es limitada, no puede comparar objetos "[], {}" o funciones dentro de estos arreglos, los arreglos en sí mismos son objetos.
let arraysHasSameElements = (arr1, arr2) => {
let count =
// returns counting of occurrences.
(arr, val) => arr.reduce((count, curr) => (curr === val ? 1 : 0) + count, 0);
/* this will return true if lengths of the arrays is equal.
then compare them.*/
return arr1.length === arr2.length
// compare arr1 against arr2.
&& arr1.reduce((checks, val) =>
/* creating array of checking if a value has equal amount of occurrences
in both arrays, then adds true 'check'. */
checks.concat(count(arr1, val) === count(arr2, val)), [])
// checking if each check is equal to true, then .every() returns true.
.every(check => check);
}
let arr1 = ['',-99,true,NaN,21,null,false,'help',-99,'help',NaN],
arr2 = [null,-99,'',NaN,NaN,false,true,-99,'help',21,'help'];
arraysHasSameElements(arr1, arr2); //true
let arr3 = [false,false,false,false,false,false],
arr4 = [false,false,false,false,false,false]
arraysHasSameElements(arr3, arr4); //true
// here we have uncommented version.
let arraysHasSameElements = (arr1, arr2) => {
let count = (arr, val) => arr.reduce((count, curr) => (curr === val ? 1:0) + count, 0);
return arr1.length === arr2.length && arr1.reduce((checks, val) =>
checks.concat(count(arr1, val) === count(arr2, val)), []).every(check => check);
}