devboell
devboell

Reputation: 1190

Ramda, array equality regardless of order

When comparing arrays, the ramda equals will return true only if two arrays hold the same values in the same order.

I need a function to check if two arrays hold exactly the same values, but ignore the order in which the values occur.

For now I am doing it this way:

const equalLength = (arr1, arr2) => arr1.length === arr2.length

export const equalIgnoreOrder = (arr1, arr2) =>
  equalLength(arr1, arr2) && equalLength(arr1, R.union(arr1, arr2))

but I am wondering if there is a more 'out of the box' solution?

Upvotes: 4

Views: 2170

Answers (1)

Scott Sauyet
Scott Sauyet

Reputation: 50797

I think your answer is fine. A slightly shorter one would be

const equalIgnoreOrder = compose(isEmpty, symmetricDifference)

This feels a bit more logical to me, as checking for the same elements feels more like a question of differences than unions; it feels closer to the mathematical idea of sets than does one that involves length. But that's a pretty minor concern here.

Upvotes: 9

Related Questions