比较两个数组的功能,以检查两个数组是否具有相同的元素。即使他们出了故障...
这对简单数组很有用。[String,Number,Boolean,null,NaN]。
我不使用.sort(),它修改了原始数组。有人说这是不好的...
警告。此函数是有限的,无法比较对象“ [],{}”或这些数组中的函数,数组本身就是对象。
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);
}