Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 285
devboell Avatar asked Oct 19 '25 05:10

devboell


1 Answers

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.

like image 153
Scott Sauyet Avatar answered Oct 21 '25 20:10

Scott Sauyet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!