javascripttypescriptuint8array

Compare equality of two Uint8Array


I am comparing two Uint8Array using CRC32 to ensure the accuracy of the data being decompressed. However, I am facing the issue of not having an API like Uint8Array.equal() to compare the arrays. Although there is Buffer.compare() available in Node.js, it is not supported in the browser, which I am also working on.

I have created a basic implementation, but I am unsure if there is a more straightforward approach or if I have overlooked any built-in comparison APIs.

function isEqual(arr1: Uint8Array, arr2: Uint8Array): boolean {
    if (arr1.length !== arr2.length) {
        return false
    }

    return arr1.every((value, index) => value === arr2[index])
}

Solution

  • You're not missing anything, there isn't currently an equality checking method for typed arrays (or regular arrays), or anything that can be succinctly used like one while remaining efficient with large arrays.

    There is a proposal out there, but it doesn't seem to be getting much traction. One of the more contentious issues is that there shouldn't be a dedicated method just for typed arrays, and there should just be a static object equality checking method.

    There isn't a standard object equality checking method yet, though proposals have been made in the past. Here's one that was withdrawn. You could of course create your own function like this, probably with a special conditions for ArrayBuffer.isView to compare the length first, before each property. There are many potential edge cases with a function like this, which is perhaps why a generic standard solution remains elusive.

    For now the best way to compare 2 typed arrays is to compare the length and loop over the values in your own function. You can do the second part with a method like every or a simple for/while loop (a simple loop is likely faster as it will have less overhead).