I want to compare the values in two arrays. The order of the values doesn't matter. Basically they are two Sets. This function returns true if the values are the same in both arrays, or false otherwise.
function compareSets(a1, a2) {
if (a1.length !== a2.length) {
return false;
}
var len = a1.length;
var a1Set = {};
// Convert a1 into a Set
for (var i = 0; i < len; i++) {
var value1 = a1[i];
a1Set[value1] = true;
}
// Compare a2 values to a1 values
for (var i = 0; i < len; i++) {
var value2 = a2[i];
if (!(value2 in a1Set)) {
return false;
}
}
return true;
}
This is an \$O(n)\$ solution which is better than the naive \$O(n^2)\$. I think it is always safe to say that if the lengths are different, the arrays are not the same.
Is there any way I can make this more concise?
set
functionality like here which has an.equals()
and.diff()
method and others for comparing two sets. More info here in this stackoverflow answer. – jfriend00 May 24 '14 at 3:12a1Set[value1] = true;
this solution is less correct than the naive? solution of storing values in an array and using index of as it won't work for non primitives (e.g. try comparing[{1: 'a', 2: 'b'}]
with[{}]
as you're storing the string representation of the object – megawac May 24 '14 at 3:35private
in javascript – megawac May 24 '14 at 3:36['a', 'a', 'b']
would be considered equal to['a', 'b', 'b']
, but not equal to['a', 'b']
. Also, lettingvar x = ['a', 'a'], y = ['a', 'b'];
, we getcompareSets(x, y) == false
butcompareSets(y, x) == true
. – David Knipe May 26 '14 at 22:15