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 = {
You can implement the following algorithm:
a
and b
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:
function sameElements(a, b)
{
if (a.length != b.length) {
return false;
}
var ourB = b.concat();
return a.every(function(item) {
var index = ourB.indexOf(item);
if (index < 0) {
return false;
} else {
ourB.splice(index, 1);
return true;
}
});
}
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.