HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

JavaScript Array Comparison (aka Set Comparison)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptarraycomparisonakaset

Problem

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?

Solution

In JavaScript objects, keys are always strings, or converted into strings. Therefore, all the elements of a1 and a2 will be compared as if they were stringified. For example, compareSets(['true'], [true]) returns true. I consider that to be unexpected behaviour that either needs to be fixed or documented.

Context

StackExchange Code Review Q#51595, answer score: 4

Revisions (0)

No revisions yet.