Created
September 18, 2020 19:08
-
-
Save arnonate/fb5afebf8720a284ce1f3bbc5c2390af to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const a = [1, 2, 3]; | |
const b = [4, 5, 6]; | |
const c = [1, 2, 3]; | |
function arrayEquals(a, b) { | |
return ( | |
Array.isArray(a) && | |
Array.isArray(b) && | |
a.length === b.length && | |
a.every((val, index) => val === b[index]) | |
); | |
} | |
arrayEquals(a, b); // false | |
arrayEquals(a, c); // true | |
// With sorting and dups | |
const d = [1, 2, 3, 1]; | |
const e = [3, 2, 1, 3]; | |
function arraysAreEqual(a, b, field) { | |
if (!Array.isArray(a) || !Array.isArray(b)) return false; | |
// Remove Dups and sort | |
let arrayA = [...new Set(a)].sort(); | |
let arrayB = [...new Set(b)].sort(); | |
if (field) { | |
// Do something with field | |
} | |
return ( | |
arrayA.length === arrayB.length && | |
JSON.stringify(arrayA) === JSON.stringify(arrayB) && | |
arrayA.every((value, index) => value === arrayB[index]) | |
); | |
} | |
console.log(arraysAreEqual(d, e)); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment