4

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?

devboell
  • 1,180
  • 2
  • 16
  • 34

1 Answers1

9

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.

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
  • thank you, I agree that `union` doesn't feel quite right here, that's what prompted me to ask the question. I had a version using `difference`, but it, as does yours, would match [1, 2, 3] and [1, 1, 2, 3]. Thinking in sets, that shouldn't be a problem, but for my use case such a state (duplicates) would indicate an error in my program. Then again, I should probably guard/validate against duplicates at the time the arrays get populated, and not when I am comparing them. – devboell Jun 11 '18 at 07:12
  • While Ramda doesn't provide a public `Set` implementation, there is an [internal version](https://github.com/ramda/ramda/blob/master/source/internal/_Set.js) which may serve s a model for how to deal with value equality for Sets. – Scott Sauyet Jun 11 '18 at 12:24
  • I like it, very clean and simple – Martin Seeler Mar 07 '19 at 17:13
  • 1
    why not just using sort? `equals(arrayA.sort(), arrayB.sort())`? – chitzui Jul 16 '20 at 10:04