I have these two arrays: one is filled with information from an ajax request and another stores the buttons the user clicks on. I use this code (I filled with sample numbers):
JavaScript
x
10
10
1
var array1 = [2, 4];
2
var array2 = [4, 2]; //It cames from the user button clicks, so it might be disordered.
3
array1.sort(); //Sorts both Ajax and user info.
4
array2.sort();
5
if (array1==array2) {
6
doSomething();
7
}else{
8
doAnotherThing();
9
}
10
But it always gives false
, even if the two arrays are the same, but with different name. (I checked this in Chrome’s JS Console). So, is there any way I could know if these two arrays contain the same? Why is it giving false
? How can I know which values in the first array are not in the second?
Advertisement
Answer
Sort the arrays and compare their values one by one.
JavaScript
1
22
22
1
function arrayCompare(_arr1, _arr2) {
2
if (
3
!Array.isArray(_arr1)
4
|| !Array.isArray(_arr2)
5
|| _arr1.length !== _arr2.length
6
) {
7
return false;
8
}
9
10
// .concat() to not mutate arguments
11
const arr1 = _arr1.concat().sort();
12
const arr2 = _arr2.concat().sort();
13
14
for (let i = 0; i < arr1.length; i++) {
15
if (arr1[i] !== arr2[i]) {
16
return false;
17
}
18
}
19
20
return true;
21
}
22