Array equality in JavaScript – functional style

So it turns out there is no built-in test for array equality in JavaScript. There are some suggestions here on StackOverflow, but I wanted to see if there was a simple answer using Functional Javascript.

Here’s my attempt:

ArrayEq: function(a1,a2) {
    return reduce("x && y",true,map("x[0]==x[1]",zip(a1,a2)));
}

Reading from right to left, the zip transforms them into an array of pairs, then each pair is compared, and then the reduce applies the && operator to each boolean result in turn.

This entry was posted in Uncategorized. Bookmark the permalink.

One Response to Array equality in JavaScript – functional style

  1. matt burns says:

    Nice.

    In practice it would be slow due to no early abort a soon as mismatch found.
    I should read up more on this map reduce stuff. I guess the advantage is that this can be parallel-ised easily so that you could give this to n threads where n is the length of array and compare in constant time for any size array (assuming n CPUs)?

Leave a Reply

Your email address will not be published. Required fields are marked *