1// compare two arrays where order might differ
2const array1 = [1,2,3,4,5];
3const array2 = [3,4,1,2,5];
4
5const compareArrays = (array1, array2) => {
6 return (
7 array1.length === array2.length &&
8 array1.every((el) => array2.includes(el));
9 );
10};
11
12compareArrays(array1, array2); // true
13
1Array.prototype.equals = function(arr2) {
2 return (
3 this.length === arr2.length &&
4 this.every((value, index) => value === arr2[index])
5 );
6};
7
8[1, 2, 3].equals([1, 2, 3]); // true
9[1, 2, 3].equals([3, 6, 4, 2]); // false
1// To compare arrays (or any other object):
2// Simple Array Example:
3const array1 = ['potato', 'banana', 'soup']
4const array2 = ['potato', 'orange', 'soup']
5
6array1 === array2;
7// Returns false due to referential equality
8JSON.stringify(array1) === JSON.stringify(array2);
9// Returns true
10
11
12// Another Example:
13const deepArray1 = [{test: 'dummy'}, [['woo', 'ya'], 'weird']]
14const deepArray2 = [{test: 'dummy'}, [['woo', 'ya'], 'weird']]
15
16deepArray1 === deepArray2;
17// Returns false due to referential equality
18JSON.stringify(deepArray1) === JSON.stringify(deepArray2);
19// Returns true
20
21