I'm looking for an efficient way to find out whether two arrays contain same amounts of equal elements (in the ==
sense), in any order:
foo = {/*some object*/}
bar = {/*some other object*/}
a = [1,2,foo,2,bar,2]
b = [bar,2,2,2,foo,1]
sameElements(a, b) --> true
PS. Note that pretty much every solution in the thread uses ===
and not ==
for comparison. This is fine for my needs though.
You can implement the following algorithm:
a
andb
do not have the same length:false
.b
,a
:b
:b
,false
.true
.With Javascript 1.6, you can use every() and indexOf() to write:
Note this implementation does not completely fulfill your requirements because
indexOf()
uses strict equality (===
) internally. If you really want non-strict equality (==
), you will have to write an inner loop instead.Like this perhaps?