2つの配列を比較して、両方に同じ要素があるかどうかをチェックする関数。故障しても…
単純な配列に適しています。[文字列、数値、ブール値、null、NaN]。
.sort()は使用しません。元の配列を変更します。悪いと言う人もいます...
注意。この関数は制限されており、Objects [[]、{} "またはこれらの配列内の関数を比較できません。それ自体がObjectである配列です。
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);
}